I have a problem with inputting a string pointer in struct. This is my code:
typedef struct{
char *name;
int age;
}stu;
void allocate(stu* &s, int n){
s = (stu*) malloc(n * sizeof(stu));
if(s == NULL){
printf("\nNot enought memory!");
exit(1);
}
}
// Input info
void input_info(stu* &s, int n){
void input(stu &s); //prototype
for(int i = 0; i < n; i++){
printf("\n-- Student #%d:", i+1);
input(*(s+i));
}
}
void input(stu &s){
fflush(stdin);
printf("\nEnter student's name: ");
gets(s.name);
printf("\nEnter student's age: ");
scanf("%d", &s.age);
}
// End input
//Output info
void output_info(stu* s, int n){
void output(stu s); //prototype
for(int i = 0; i < n; i++){
printf("\n-- Student #%d:", i+1);
output(*(s+i));
}
}
void output(stu s){
printf("\nName: %s", s.name);
printf("\nAge: %d", s.age);
}
//End output
int main(){
stu* s;
int n;
printf("How many students you want to input?: ");
scanf("%d", &n);
allocate(s, n);
input_info(s, n);
output_info(s, n);
getch();
}
When I input second student's name, it's breaked? I allocated memory. And I want to ask how to deallocate memory for stu pointer? Thanks for reading