The scanf
function takes the address of a variable to put the result into.
Writing scanf("%d", &someVar)
will pass the address of the someVar
variable (using the &
unary operator).
The scanf
function will drop a number into the piece of memory at that address. (which contains your variable)
When you write scanf("%d", age)
, you pass the value of the age
variable to scanf
. It will try to drop a number into the piece of memory at address 0
(since age
is 0
), and get horribly messed up.
You need to pass &age
to scanf
.
You also need to allocate memory for scanf
to read a string into name
:
char name[100];
scanf("%99s
", name);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…