Can someone please review my code? Its supposed to store 3 student's first name, last name and ID number into an array and then print them out, but I keep getting a segmentation fault after entering the 3rd students info.
#include %26lt;stdio.h%26gt;
struct student_record
{
int firstn;
int lastn;
int id;
};
int main()
{
int i, j;
struct student_record students[3];
for(i=0; i%26lt;=2; i++)
{
printf("Entry %i\n", i+1);
printf("First name\n");
scanf("%s", %26amp;students[i].firstn);
printf("Last name?\n");
scanf("%s", %26amp;students[i].lastn);
printf("ID?\n");
scanf("%s", %26amp;students[i].id);
}
for(j=0; j%26lt;=2; j++){
printf("Student %i\n", j+1);
printf("Name: %s %s\n", students[j].firstn, students[j].lastn);
printf("ID: %s\n", students[j].id);
}
return 0;
}
C programming help?
I think you might want to use %d instead of %s for integers...
For more tips, visit http://www.mycsharpcorner.com
Reply:I think you are missing a "," a period after :struct student_record
Reply:Probably not the reason but why are you defining three integers for what are really three char *?
On theme now, which compiler/OS are you in?
Reply:when your getting the ID's from the user you want to use %d if they are integers or %f if they are anything longer than an int. I bet using %s to get the ID's is causing it to store more information than an int can hold so thats whats throwing your error.
Reply:Have you covered strings yet in your programming class? Recall that a char is *one* character. Like 'a'. Or 'z'. So something like 'Michael' is *many* characters or a string. Clearly, char firstn is inappropriate, because you want a string.
Do some reading: http://www.cprogramming.com/tutorial/c/l...
So there's a few different things you can do. You can use a char* in your struct which will point to a C string. Or create an array like char firstn[50] and scanf into that array.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment