为什么我们不使用'和;'在scanf中的字符arrray [英] why we do not use '&' in scanf for char arrray

查看:150
本文介绍了为什么我们不使用'和;'在scanf中的字符arrray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int age;
char name[10];

scanf("%d", &age);
scanf("%s", name);

在我们使用第一 scanf函数函数'和; 符号岁以前,但在第二个 scanf函数我们不使用'和;
因为它是一个字符数组。谁能告诉我,为什么会这样?

In first scanf function we use '&' symbol before age, but in second scanf we don't use '&' as it is a char array. Can anybody tell me why is so?

推荐答案

在大多数情况下,类型的前pression T N个元素的数组将被转换为(衰变),键入指针 T ,和前pression的价值将是第一个元素的地址数组。

Under most circumstances, an expression of type "N-element array of T" will be converted to ("decay") to type "pointer to T", and the value of the expression will be the address of the first element in the array.

当你写

scanf("%s", name);

恩pression 名称的类型为字符 10元素的数组根据上面的规则,它被转换为类型指针字符,它的价值是一样的&放大器;名称[0] 。因此, scanf函数接收一个指针值,而不是一个数组值。

the expression name has type "10-element array of char"; by the rule above, it is converted to type "pointer to char", and its value is the same as &name[0]. So scanf receives a pointer value, not an array value.

此规则的例外是当数组前pression是的sizeof _Alignof ,或者一元&安培; 运营商,或者是文字被用来初始化声明另一个数组的字符串。

The exceptions to this rule are when the array expression is an operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize another array in a declaration.

请注意,我们的前pressions 名称&放大器;名称会给你同样的的(数组的第一元素的地址是相同的数组的地址),但它们的类型将是不同的; 名称将键入的char * ,而&放大器;名称将有键入字符(*)[10] 或指向10个元素的数组字符的。

Note that the expressions name and &name will give you the same value (the address of the first element of the array is the same as the address of the array), but their types will be different; name will have type char *, while &name will have type char(*)[10], or "pointer to 10-element array of char".

这篇关于为什么我们不使用'和;'在scanf中的字符arrray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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