I need to implement a variable length data array containing void pointers. And I ran into the problem that when trying to print from this array I always output the last element. Here is an abstract illustration of my problem and attempted implementation:
#include <stdio.h>
#include <stdlib.h>
int main() {
int capacity = 4; // for example
void **array = malloc(capacity*sizeof(void*));
// assign values to array elements
for(int i = 0; i < capacity; i++) {
array[i] = malloc(sizeof(void*)); // not sure if it necessary
int a = i*i;
array[i] = &a;
printf("index: %d, element: %d\n", i, *(int*)array[i]); // for demonstration
}
printf("\n");
/*
* after that I try to print all the elements of the array sequentially
*/
for(int i = 0; i < capacity; i++) {
printf("index: %d, element: %d\n", i, *(int*)array[i]));
}
// I know that I do not free my memory, but that’s not the point
return 0;
}
Output that i get looks like:
index: 0, element: 0
index: 1, element: 1
index: 2, element: 4
index: 3, element: 9
index: 0, element: 9
index: 1, element: 9
index: 2, element: 9
index: 3, element: 9
(Edit the questions: in the comments they pointed out to me that the error was in the way of putting the variable in the mass, because I did not take into account the lifetime of the variable in the for-loop and the principle of the pointer) How can I correctly fill a similar array without introducing a bunch of extra variables? Or the method that I chose is completely incorrect? I would be grateful for any help
array[i] = &a;stores pointers to a variable that's local to the loop - after the loop ends you have a lot of dangling pointers in your arrayarray[i] = ...followed byarray[i] = ...really does.