Reputation: 439
I am about to create a programm which stores data of students in a list. My question is, how to shall I allocate memory for each char string in my struct array. My code is down below. If there're some other mistakes, please correct me.
#include <stdio.h>
#include <stdlib.h>
#define DATA 10;
#define NAME 10;
typedef struct{
int id;
char *givenname;
char *familyname;
} students;
int main()
{
int answer;
int incr = 0; // Index for students in the list
int datalen = DATA;
int namelen = NAME;
students *studentlist;
studentlist = malloc(datalen * sizeof(students)); // Allocate memory for first ten students
if(NULL == studentlist){
printf("Error: Couldn't allocate memory\n");
exit(0);
}
for(incr = 0; incr < datalen; incr ++){
printf("Add student to the list? Yes(1) No(2)\n");
scanf("%d", &answer);
if(answer != 1){
break;
}
studentlist[incr]->givenname = malloc(namelen * sizeof(char)); // Allocate memory for each name
studentlist[incr]->familyname = malloc(namelen * sizeof(char));
printf("Insert ID: ");
scanf("%d", &studentlist[incr].id);
printf("Insert given name: \n");
scanf("%s", studentlist[incr].givenname);
printf("Insert family name: \n");
scanf("%s", studentlist[incr].familyname);
}
free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);
return 0;
}
Upvotes: 1
Views: 698
Reputation: 26
Reference of some elements is wrong:
studentlist[incr]->givenname
It should be:
studentlist[incr].givenname
Allocation of strings seems fine.
Your freeing code needs change:
free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);
You need to free studentlist.givename and studentlist.familyname in a loop and then free studentlist at the end:
for(incr = 0; incr < datalen; incr ++){
free(studentlist[incr].givename);
free(studentlist[incr].familyname);
}
free(studentlist);
Upvotes: 1