c - 一个数组的地址返回什么?

标签 c arrays pointers

我认为当您尝试获取数组的地址时,它会返回它所包含的第一个元素的地址。

int *j;
int a[5]={1,5,4,7,8};

现在 j=&a[0]; 工作得很好。

甚至 j=a 也有同样的功能。

但是当我执行 j=&a 时,它会抛出一个错误,提示 cannot convertint (*)[5]' to int*' in assignment

为什么会这样? &a 应该是数组 a 的第一个元素,所以它应该给出 &a[0]。 但它会抛出一个错误。谁能解释一下为什么?

最佳答案

C 标准说明了数组在表达式中的使用方式(摘自 C99 6.3.2.1/3“左值、数组和函数指示符”):

Except when it is the operand of the sizeof 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

这通常被称为“数组衰减为指针”。

因此,以下较大表达式中的子表达式 a 的计算结果为指向 int 的指针:

  • j=&a[0]
  • j=a

在更简单的表达式 j=a 中,该指针被简单地分配给 j

在更复杂的表达式 j=&a[0] 中,“索引”运算符 [] 应用于指针(相当于 *(a + 0)) 并将“寻址”运算符应用于它,导致另一个指向 int 的指针被分配给 j

在表达式 j=&a 中,取地址运算符直接应用于数组名称,我们遇到了上面引用子句中的一个异常:“Except when it is the operand的...一元 & 运算符”。

现在,当我们查看标准关于一元 &(地址)运算符(C99 6.5.3.2/3“地址和间接运算符”)的内容时:

The unary & operator returns the address of its operand. If the operand has type "type", the result has type "pointer to type".

由于 a 的类型为“array of 5 int” (int [5]),因此直接对其​​应用 & 的结果为键入“指向 5 个 int 数组的指针”(int (*)[5]),它不能分配给 int*

关于c - 一个数组的地址返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22342438/

相关文章:

c++ - 返回 vector 元素 C++ 的地址

c - 链表、指针和节点

c - 类型转换 void 指针到 int 和 string

javascript - 使用 php 解析 Javascript 数组或对象

PHP 数组语法/运算符?

c - fseek 和 fread C 编程

C VS2010 - 堆损坏释放结构上的指针数组

c - 在c编程中如何将从文件读取的数据作为字符串存储在数组中?

javascript - 异步构建一个数组,迭代其他数组

c - 如何指定在支持 2 个不同设备的驱动程序中打开哪个设备?