Dynamic allocation of an array of structures

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.

+6
source share
1 answer

The error is here:

 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); } 

you should do this:

 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); } 

The reason is because you are indexing the wrong "dimension" data .

+6
source

Source: https://habr.com/ru/post/899894/


All Articles