Why scanf(“%s”,&str); behaves as scanf(“%s”,str);? [duplicate]

大兔子大兔子 提交于 2019-12-22 10:06:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!