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;
}
studentlist[incr]->givenname-->studentlist[incr].givennamestudentlist.givename(and familyname) beforestudentlistor else you're invoking undefined behaviour (accessing freed memory). 3. Infact how can you free studentlist then access by.? If you freed it it ,must be a pointer and so access via->. - Does this even compile?free(studentlist.givename);--> do each elementfree(studentlist[incr].givename);and beforefree(studentlist);