I am getting Segmentation error when i try to run this code.
#include <stdio.h>
int main() {
int a = 0;
printf("Enter a number");
scanf("%d", a);
}
This is the error showing: enter image description here
I don't know what went wrong,
CodePudding user response:
You need to check how scanf
is used at the document.
int scanf(const char *format, ...)
You have to pass the pointer of a
ref. https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
CodePudding user response:
scanf
takes a format string and a matching set of pointers. You haven't passed a pointer, but rather the value of a
. In this case, that's 0
.
Now, both of these are numeric types, so this does compile, but scanf
attempts to dereference 0
and assign to it, which causes a segmentation fault.
This can be seen in a very simple program.
int main() {
int a;
*(int *)a = 42;
return 0;
}