-
Segmentation Fault
I am new at C, and I made a program to test out my newly acquired knowledge of functions. Here is what the code looks like:
Code:
/* This is to test functions, and hopefully comparitive/logical operators */
main()
{
char reply;
int output;
printf("Do you want to (a)dd or (s)ubtract the numbers 5 and 4?");
scanf("%c",reply);
switch (reply) {
case 'A':
output = Add();
break;
case 'S':
output = Subtract();
break;
default:
printf("Input Error. Use the letters A or S next time.");
}
printf("Done. %d",output);
}
int Add()
{
int output;
output=5+4;
return(output);
}
int Subtract()
{
int output;
output=5-4;
return(output);
}
This code compiles fine, with no errors or warnings. Then, when I run it and type in A or S at the printf statement, it says "Segementation Fault". I have no idea what that means, but I get it a lot on programs. Before, I just gave up, but now it is getting annoying and I want to know what I'm doing incorrectly.
I am using GCC to compile the program, GVIM to program it, and Debian GNU/Linux as my operating system.
-
>scanf("%c",reply);
reply isn't a pointer, which scanf expects, so you need to pass the address:
Code:
scanf("%c", &reply);
-
note: be careful with scanf("%c",&whatever); because in usual cases, the carriage return is left in the input buffer.
another thing:
please use int main()
otherwise you'll be flamed to death.
Code:
int main()
{
//stuff goes here
return 0;
}
-
With Scanf
Point to note!!
Whenever you are using Scanf(), remember it's a function, you must include the address operator with the variable..e.g
scanf("%d", &var_name);
where var_name represents your variable name..
since scanf is deals with input , it need to know the address of whatever it's working with...which you get by using &