user4368627
user4368627

Reputation:

Allocating a Dynamic array of structs in C

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.

Upvotes: 0

Views: 84

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You need space to store the input:

printf("Enter Name1: ");
fgets(namePointer[i]->Name1, 50, stdin); /* Name1 is an uninitialized pointer  */
stringLen = strlen(namePointer[i]->Name1) + 1;
namePointer[i]->Name1 = realloc(namePointer[i]->Name1, sizeof(char) * stringLen);

Use an intermediate array and strcpy:

char temp[50];
printf("Enter Name1: ");
fgets(temp, sizeof temp, stdin);
stringLen = strlen(temp) + 1;
namePointer[i]->Name1 = realloc(namePointer[i]->Name1, sizeof(char) * stringLen);
strcpy(namePointer[i]->Name1, temp);

Or use strdup (non standard but available on many implementations):

char temp[50];
printf("Enter Name1: ");
fgets(temp, sizeof temp, stdin);
namePointer[i]->Name1 = strdup(temp);

Upvotes: 1

Related Questions