为什么scanf函数(QUOT;%S",&安培; STR);表现为scanf函数(QUOT;%S",STR);? [英] Why scanf("%s",&str); behaves as scanf("%s",str);?

查看:182
本文介绍了为什么scanf函数(QUOT;%S",&安培; STR);表现为scanf函数(QUOT;%S",STR);?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面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;
}

下面是输入和输出:

abc
abc     3
123
123     3

据我们所知, scanf函数是一个变量参数函数,所以当它被称为其参数将不投。这样一来,参数必须在类型传递他们应该是什么。然而, STR 的类型是的char * (从腐朽的char(*)[80 ] ),而&放大器; STR 字符(*)的类型[80] ,虽然它们具有相同的,即&放大器;海峡[0]

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].

那么,为什么 scanf函数(%S,&安培; STR); 正常工作,而不会导致段错误,由于指针运算

So why can scanf("%s",&str); work properly without causing segfault due to pointer arithmetic?

推荐答案

这两个指针值( STR &放大器; STR )具有相同的二进制值, STR 即地址。他们这样做,不过,有不同的类型:当作为参数传递, STR 转换为类型的char * ,而&放大器; STR 的类型字符(*)[80] 。前者是正确的,而后者则是不正确。它的工作原理,但您使用了不正确的指针类型,而事实上 GCC 警告有关不正确的参数类型 scanf函数

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.

这篇关于为什么scanf函数(QUOT;%S&QUOT;,&安培; STR);表现为scanf函数(QUOT;%S&QUOT;,STR);?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆