I found useful answers to other people's questions countless times here on stackoverflow, but this is my first question with a question about my own.
I have a C function that should dynamically allocate space for an array of structures, and then populate the structure elements of each array element with values ββpulled from the file. Assigning members works fine in the first pass of the loop, but I get a segmentation error in the second pass.
I wrote this quick program illustrating the essence of the problem I am having:
#include <stdlib.h> #include <stdio.h> typedef struct { int a; int b; } myStruct; void getData(int* count, myStruct** data) { *count = 5; *data = malloc(*count * sizeof(myStruct)); int i; for (i = 0; i < *count; i++) { data[i]->a = i; data[i]->b = i * 2; printf("%da: %d\n", i, data[i]->a); printf("%db: %d\n", i, data[i]->b); } } int main() { int count; myStruct* data; getData(&count, &data); return 0; }
The output I get from this is:
0.a: 0 0.b: 0 Segmentation fault
I am not sure where my problem is. It seems that calling malloc allocates enough space for one structure, when it should allocate space for five.
Any help would be greatly appreciated.
source share