I'm trying to understand how a pointer to an array of pointers works.
I have the following struct
typedef struct Array {
int capacity;
int size;
void **items;
} Array;
and the following function which allocates memory for the struct and returns a pointer to it
Array *createArray(int capacity) {
Array *array = malloc(sizeof(Array *));
array->capacity = capacity;
array->size = 0;
void **items = malloc(sizeof(void *) * array->capacity * sizeof *items);
if(items == NULL) {
exit(1);
}
array->items = items;
return array;
}
Now, I want to initialize an array of pointers to this struct. Here's how I am doing that
Array *(*createHashTable(int size))[10] {
Array *array[10];
int i = 0;
for(i = 0; i < size; i++) {
array[i] = createArray(size);
}
Array *(*ptr)[10] = &array;
for(i = 0; i < size; i++) {
printf("%d\n", (*(ptr[0] + i))->capacity);
}
return ptr;
}
The print statement gives me what I expect: which is
10
10
10
10
10
10
10
10
10
10
Now, my main function
int main(int argc, char *argv[]) {
Array *(*ptr)[10] = createHashTable(10);
printf("%d\n", (*(ptr[0]+9))->capacity);
return 0;
}
So far, everything makes sense to me, with the printf statement in main working fine. However, the part that confuses me is if I place a for loop inside my main function like so
int main(int argc, char *argv[]) {
Array *(*ptr)[10] = createHashTable(10);
int i = 0;
for(i = 0; i < 10; i++) {
printf("%d\n", (*(ptr[0] + i))->capacity);
}
return 0;
}
I get the following output,
10
10
Segmentation fault: 11
Why is my program seg faulting only when I loop? Am I missing something basic about returning a pointer to an array of pointers?
Array *array = malloc(sizeof(Array *));->Array *array = malloc(sizeof(Array));sizeof(*VARIABLE). For instanceArray *array = malloc(sizeof(*array))would never be wrong. Even if you changeArray *array;toArray ****array;! Oh, and that's an interesting return type for a function, not to mention that it makes c a weird language.sizeof(Array *)is equal to the size of any pointer, evensizeof(void *), so it's allocating either 4 or 8 bytes, depending on the platform and OS. But you really, needsizeof(Array)bytes to allocate.