0

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 pQueue[qSize];
    int i;
    float t;
    for(i = 1; i < qSize; i++)
    {
        t = getNextRandomInterval(getL());
        pQueue[i] = createEvent(t); 
    }

    setpQueue(pQueue);
    buildpQueue();

}

I use setpQueue(pQueue) to set the global variable....like so...

void setpQueue(EventPTR* pQueue)
{
    pQueuePTR = pQueue;
}

The global variable is declared as:

EventPTR* pQueuePTR;

Here is my struct: (in my .h file.. atm)

struct event {
    float eTime;
    double sTime;
    int status;
};

typedef struct event Event;
typedef struct event* EventPTR;

Everything is awesome up till this point. My buildpQueue even works right... using the pQueuePTR .... however...I went to make some test functions to just output the pQueue array and this is where it got ugly...

void outTest()
{
    int i;
    printf("\n\n");
    for(i = 0; i < qSize; i++)
    {
        if(pQueuePTR[i] != NULL) printf("%f ", pQueuePTR[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... :)

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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...
You can also add static to your declaration of pQueue. Then it will remain existing even after returning from initPQueue function.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.