Home > Mobile >  How to initialize an array of pointers to a struct in a loop?
How to initialize an array of pointers to a struct in a loop?

Time:03-03

struct stack {
    int pointer;
    int *nums;
};

I want to initialize an array of pointers to this struct, but somehow all of those pointers are pointing to the same location. Later on, when I change the st_ptr->pointer in one of them, all of them are changed, which is not the behavior I want.

This is how I implemented it:

stack* stacks[100];
int count = 0;
for(int i=0; i<100; i  ){
    struct stack *st_ptr, st;
    st_ptr = &st;
    st_ptr -> pointer = -2;
    stacks[i] = st_ptr;
}

CodePudding user response:

Your current code fills each slot in your pointer array with the address of an automatic variable that ultimately expires after each iteration of the for loop. What you have left is an array filled with dangling pointers.

Regarding your initial fundamental question, how to initialize an array of pointers...

stack *stacks[100] = {0};

There. They're initialized, and every one of them has a determinate initial value of NULL. I suspect you want more....

What I think you're really asking is how to populate an array of pointers in such a way that each element points to its own distinct dynamic object. Before I answer that, a more basic question: What problem are you attempting to solve with that array that would not be addressed by simply using an array of stack, not stack * ? Unless you have a good reason for the latter, the former is usually preferred. Consider that.

Anyway, this is how you could do what you seem to be attempting.

stack* stacks[100];
for(int i=0; i<100; i  )
{
    stacks[i] = (stack *)malloc( sizeof **stacks );
    if (stacks[i] == NULL)
    {
        perror("Failed to allocate new stack");
        exit(EXIT_FAILURE);
    }
    stacks[i]->pointer = -2;
}

The down shot is now you have 100 individual dynamic allocations, each of which must be free()'ed sooner or later.

That said, this is tagged C for some reason, so why you're not just using standard containers and/or smart pointers remains a mystery.

CodePudding user response:

struct stack *st_ptr, st;

The instance of stack here has automatic storage duration. The lifetime and storage duration of that object ends at the end of the scope where it was declared which in this case is the end of the block statement that is being looped over. After the block ends, the pointer stored in the array becomes invalid.

All pointers in your array are invalid.


It appears that you want the pointers to point to 100 different instances of stack, which should exist simultaneously. There's a convenient way to create 100 objects: You could use an array. Here is an example:

constexpr std::size_t count = 100;
stack stack_instances[count]{};
for (auto& stack : stack_instances) {
    stack-> pointer = -2;
}

It's unclear why you want to have an array of pointers. I urge you to think about why you think that you need it; perhaps this array of stacks would be sufficient by itself

But, you can create such an array of pointers pointing to those stacks if you so wish:

stack* stacks[count];
for(std::size_t i = 0; i < count; i  ){
    stacks[i] = stack_instances   i;
}

You should make sure that the life time of stack_instances exceeds the life time of stacks.

  • Related