-
Segmentation Fault hmm?
Hey guys I'm trying to get this to work, it does the first loop in main and asks for the names/year etc, but once I type the year it says "Segmentation fault" and kills the program! If someone could please tell me what Segmentation Fault means that would be great, Also yes I realise I probably should be using fgets instead of fscan but i'm familiar with fscan so I'm sticking with it for this program. But if that's the actual issue then I guess I'll have to change it. Thanks!
[B]EDIT: Yay I fixed it, someone on IRC told me that I needed & infront of "scanf("%d", records[x].yearborn);" i.e "scanf("%d", &records[x].yearborn);", the only problem is I don't understand WHY :P If someone could help explain that'd be great!
Code:
#include <stdio.h>
struct rec
{
char firstname[20];
char lastname[20];
int yearborn;
} records[5];
int main()
{
int x;
int y;
for (x=0; x < 5; x++)
{
printf("Please enter the FIRST name of #%d. member!\n", x+1);
scanf("%s", records[x].firstname);
printf("Please enter the LAST name of #%d. member!\n", x+1);
scanf("%s", records[x].lastname);
printf("Please enter the year this member was born!\n");
scanf("%d", records[x].yearborn);
}
for (y=0; y < 5; y++)
{
printf("Record %d, First Name: %s\n", y, records[y].firstname);
printf("Record %d, Last Name: %s\n", y, records[y].lastname);
printf("Record %d, Year Born: %d\n", y, records[y].yearborn);
printf("-------------------------------------\n");
}
return 0;
}
-
Change
Code:
scanf("%d", records[x].yearborn);
to
Code:
scanf("%d", &records[x].yearborn);
EDIT: I see someone already told you the answer 1 minute before i posted =D
-
Yup got that, but knowing WHY would be helpful :)
-
You were passing the value of yearborn to scanf. In order for a function to modify the value of one of the function parameters, that parameter needs to be the pointer to the variable, not the actual value. Putting "&" in front gets the pointer to the variable so scanf can change the pointers value.
Heres an example:
Code:
void ChangeMe(int a)
{
a = 32;
}
int a = 16;
ChangeMe(a);
printf("%i\n", a); //It still prints 16 rather than 32.
You would use this instead:
Code:
void ChangeMe(int* a)
{
*a = 32;
}
int a = 16;
ChangeMe(&a);
printf("%i\n", a); //a has been changed after calling ChangeMe
-
http://cpwiki.sourceforge.net/A_pointer_on_pointers
It is critical that you understand this.
Also read http://cpwiki.sourceforge.net/buffer_overrun and fix your scanf lines.
Even better is to use fgets.