问题
Look at the following code:
#include <stdio.h>
int main()
{
char str[80];
int n;
scanf("%s%n",str,&n);
printf("%s\t%d",str,n);
putchar('\n');
getchar(); //to remove '\n'
scanf("%s%n",&str,&n);
printf("%s\t%d",str,n);
return 0;
}
Here is the input and output:
abc
abc 3
123
123 3
As we know, scanf
is a variable parametric function, so its parameters will not be cast when it's called. As a result, parameters must be passed in the type exactly what them should be. However, the type of str
is char *
(decayed from char (*)[80]
), while &str
has the type of char (*)[80]
, although they have the same value, namely &str[0]
.
So why can scanf("%s",&str);
work properly without causing segfault due to pointer arithmetic?
回答1:
The two pointer values (str
and &str
) have the same binary value, namely the address of str
. They do, however, have different types: When passed as an argument, str
is converted to type char *
, while &str
has type char (*)[80]
. The former is correct, while the latter is incorrect. It works, but you are using an incorrect pointer type, and in fact gcc
warns about the incorrect argument type to scanf
.
来源:https://stackoverflow.com/questions/34704302/why-scanfs-str-behaves-as-scanfs-str