I'm trying to create an array of structs using dynamic memory allocation. My struct is something along the lines of:
typedef struct {
char data1[200];
char data2[200];
char data3[200];
int data4;
double data5;
double data6;
} randomInfo_t;
I don't know how many of these structs I need to create, which is why I'm using malloc() to dynamically create the array.
There are multiple lines of data stored within a file, similar to a CSV.
Right now, my attempt at creating the array has lead to a segmentation fault, which I suspect is due to the way I'm using malloc():
randomInfo_t *stuffArray;
int indexCounter=0;
while(fgets(buffer, 1024, fp)) {
/* some random code here */
stuffArray[indexCounter] = *(randomInfo_t *)malloc(sizeof(randomInfo_t *));
assert(stuffArray[indexCounter] != NULL);
char *readLine = strtok(buffer, " ");
while(readLine) {
strcpy(randomArray[indexCounter].data1, readLine);
etc...
}
indexCounter++;
}
I've tried debugging it myself, but I have absolutely no clue what I was doing.
Any help is appreciated. Thanks
(PS. I know that using a linked list would be a lot easier, and I would prefer to use one as well, but requirements of the code means no linked lists).
stuffArrayis a pointer. What is it pointing to?randomInfo_tor do you want to allocate memory for an array ofrandomInfo_t *with each element pointing to a separately allocatedrandomInfo_t? Your code is all wrong, so it is hard to tell which option you are trying to implement.reallocto extend thestuffArraymemory dynamically.