Reputation: 45
I have the following struct:
struct student {
char *firstName;
int exam1;
};
The rest of the code is in the main function. I ask the user for how many students they have in a class and store that in numStudents:
int numStudents;
cout << "How many students do you have in your class? ";
cin >> numStudents;
Now I have to create a dynamic array to store the name of numStudents, and ask the user to input the name and exam score for the number of students entered earlier. This is the code I have so far. Cin works. But when I try to output, the system just exits.
student *ptr = new student[numStudents];
cout << "Enter name, exam1 for each student: ";
for(i = 0; i < numStudents; i++)
{
cin >> ptr[i].name;
cin >> ptr[i].exam1;
}
for(i = 0; i < numStudents; i++)
{
cout << ptr[i].name;
cout << ptr[i].exam1;
}
Upvotes: 2
Views: 57
Reputation: 46
ptr is the array and not ptr.name ... What you are actually doing is treating the properties of the first item in the array as if they were the arrays .but it's not the case . You should change it to :
student *ptr = new student[numStudents];
cout << "Enter name, exam1 for each student: ";
for(i = 0; i < numStudents; i++)
{
cin >> ptr[i]->name;
cin >> ptr[i]->exam1;
}
You can also read more about this error message in this answer
Upvotes: 2