my problem today is that I need to allocate a dynamic array of structs. I have coded my entire program, but I am getting seg faults and I believe it is because I have not allocated things properly. Overall I would just like some more information on how to do this, and where I went wrong. Thanks!
Here is my struct:
struct names {
char *Name1;
char *Name2;
};
struct names **namePointer = NULL;
Here is where I want to allocate for the number of structs in the array where numOfElems is a variable which will count how many iterations I need. Currently it is set to 1 and will grow one each time I need more space:
numOfElems = 1;
*namePointer = realloc(*namePointer, sizeof( struct names) * numOfElems);
Here is how I want to get input, and then store the values for the structs in the array. The string was allocated before, and then reallocated for the amount of characters as this was a specification:
printf("Enter Name1: ");
fgets(namePointer[i]->Name1, 50, stdin);
stringLen = strlen(namePointer[i]->Name1) + 1;
namePointer[i]->Name1 = realloc(namePointer[i]->Name1, sizeof(char) * stringLen);
At the end of the loop there is a "i++" and then it goes through the whole process again as to hopefully submit the next values into the next spot in the struct array. I get a seg fault and am unsure of why. If there is an easier way to dynamically allocate an array of structs please share!
Thanks again.
struct names**type?namePointershould be of typestruct names *namePointer;with one star, not two. If you have an array ofint, you useint *ptrIntArray;— similarly with an array ofstruct names. As written, you have allocated more memory than needed in the array of pointers to structures, but you've not allocated anything for the pointers to point at.