0

In this program, there are 100 different runs. For each run, an array of pointers needs to be created. The amount of pointers in each array is determined by a defined constant called NUM_POINTERS. The weird part about this program is that the array must be statically allocated, as well as the data that the pointers are pointing to.

This is my code:

for (int j = 0; j < 100; j++){
    SomeType *arr[NUM_POINTERS];

    for (int k = 0; k < NUM_POINTERS; k++){
      SomeType blah;
      blah.data = NULL;
      arr[k] = &blah;
    }

}

Now this code does not work at all. It does not create a new array for every run, and if arr[1] is changed, then every other array element gets changed as well.

I know that the easy way to fix this would be to use malloc, however that would be considered dynamically allocating, not statically. Is there any way to make it work while still having everything statically allocated?

3
  • 1
    Now this code does not work at all. - No. This code works, what is not working is your later assumption that arr is containing valid pointers. It is not, because the objects with automatic storage class (and not static as you are saying) these were pointing to went out of scope and were "destroyed". Commented Dec 9, 2021 at 21:12
  • The answer is right there in your question: Declare the array to be static. Commented Dec 9, 2021 at 21:16
  • 1
    @Barmar Won't help. blah is automatic Commented Dec 9, 2021 at 21:17

1 Answer 1

2

Declare an array of pointers and an array of structures. Then assign the pointers from the addresses of the structure array elements.

Sometype *arr[NUM_POINTERS];
Sometype arr2[NUM_POINTERS];

for (int i = 0; i < NUM_POINTERS; i++) {
    arr[i] = &arr2[i];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.