Reputation: 23
I am trying to write simple program to collect data for certain number of students and output it in the end. After I enter data for one student, my program crashes.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Student Student;
struct Student{
char name[20];
char lastname[20];
int age;
};
main() {
int i;
int n;
scanf("%d",&n);
Student *pStudents = NULL;
pStudents = (Student*)malloc(n*sizeof(Student));
for(i=0;i<n;i++) {
printf("Enter the students name: \n");
scanf("%s",(pStudents+i)->name);
printf("Enter lastname: \n");
scanf("%s",(pStudents+i)->lastname);
printf("Enter age: \n");
scanf("%d",(pStudents+i)->age);
}
for(i=0;i<n;i++) {
printf("%s",(pStudents+i)->name);
printf("%s",(pStudents+i)->lastname);
printf("%d",(pStudents+i)->age);
}
}
Thanks in advance.
Upvotes: 0
Views: 196
Reputation: 145829
scanf("%d",(pStudents+i)->age);
the argument of scanf
must be of a pointer type.
Change (pStudents+i)->age
to &(pStudents+i)->age
.
Upvotes: 5