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?