c - 单个数组元素会衰减为指针吗?

标签 c arrays pointers addressof

我知道数组会衰减为指针。因此,因为它的行为类似于指针,所以它基本上可以传递给带有需要内存地址的参数的函数,而无需使用 & 符号。例如:

char name[10];
scanf("%s", name);

是正确的。

但是,假设我只想填写'name'数组的第一个元素,为什么我不能把它写成

scanf("%c", name[0]);

但必须在'name[0]'前面写上&符号?这是否意味着单个数组元素不会衰减为指针并且不保存它们的单个内存地址而不是它们的整个数组对应物?

最佳答案

数组在作为函数参数传递时衰减为指向第一个元素的指针,而不是数组元素

引用 C11,章节 §6.3.2.1/p3,左值、数组和函数指示符,(强调我的)

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

数组元素不是数组类型,数组变量是。换句话说,毕竟数组名称与 (ny) 数组元素不同。

因此,单个数组元素不会衰减为指向任何东西的指针,即使作为函数参数传递也是如此。

关于c - 单个数组元素会衰减为指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985814/

相关文章:

c - 注意带有 R 代码的 C 函数名称

arrays - PowerShell - 将扩展参数传递给 Start-Job cmdlet

c++ - 为函数内部的结构分配和初始化值

c - 海龟图形程序没有输出

c++ - torrent 文件使用什么类型的编码以及如何附加跟踪器?

c - 回文仅在末尾比较标点符号,使用指针

Java ArrayList 的数组包含返回意外结果

java - 我如何使用此代码更改为没有任何数组?

c - qsort如何修改指向字符串的指针?

C++:用变量推导。一小段代码有问题