Global variable array pointer C programming?

In initPQueue(), pQueue is allocated on the stack; as soon as that function returns, that memory is not valid anymore.

Up vote 0 down vote favorite share g+ share fb share tw.

I'm currently working on a project where I need an array of pointers to some structs. I have created a global variable for the functions that manipulate this array to hold the pointer to that array so I can easily access it with the functions. However, I'm running into some problems where the pointer just...changes and isn't pointing to the right thing anymore.

I create the array like so: void initPQueue() { EventPTR pQueueqSize; int i; float t; for(i = 1; I eTime); else printf("NULL "); } } This gives me output like the pointer to the array contains null values when it does not... this function and the last two are all in the same file. I even put this loop in the setpQueue and it worked fine... as it should in outTest... I don't understand why this would do this... so I've come asking the experts... :) Any help would be great... :) c arrays pointers data-structures link|improve this question asked Feb 17 '11 at 21:03Bri20719 80% accept rate.

In initPQueue(), pQueue is allocated on the stack; as soon as that function returns, that memory is not valid anymore. To have the data survive the function call, you need to allocate it on the heap using malloc() (or some other memory allocation function).

This makes no sense though because the array is still there when I use other functions. Well.. I guess that would be because I am technically still within the function while calling the other one. I see... – Bri Feb 17 '11 at 21:13 1 You can also add static to your declaration of pQueue.

Then it will remain existing even after returning from initPQueue function. – mizo Feb 17 '11 at 21:18.

Once initPQueue finishes your queue will no longer exist (since it is a local variable).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions