Reputation: 1
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?
Upvotes: 0
Views: 142
Reputation: 781058
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];
}
Upvotes: 2