gpt4 book ai didi

c - 为什么取消引用指向整数数组(在二维数组中)的指针会返回(或衰减到)指向第一个元素的指针?

转载 作者:太空狗 更新时间:2023-10-29 16:01:42 25 4
gpt4 key购买 nike

我已经阅读了很多关于指针和二维数组关系的帖子,但我似乎无法理解概念。假设有一个二维数组 int a[3][2] 和一个数组 int b[2]
现在 a 返回一个指向大小为 3 的整数数组的指针。它将是 int (*)[2] 类型。

随着我对这个概念的理解,取消引用它 (*a) 会给我数组本身,这会衰减到指向一维数组第一个元素的指针,并且是类型(int*) 。现在大胆的部分是怀疑。

为什么如何这种衰减发生在数组本身(这是完整的一维数组 a[0])衰减到一维数组的第一个元素的地方?
(似乎无法理解为什么和如何部分) 并且似乎也无法在其他链接上找到它。

a[0]一样,*a,&a[0][0]代表同一个指针。这里 a[0] 是第一个 1d 数组。那么 b(上面声明的)和 a[0] 是否代表相同的东西(都是一维数组,然后衰减到指向数组中第一个元素的指针)输入(整数*)?

最佳答案

why and how does this decay happen where the array itself decays to first element of the 1d array?

C11:6.3.2.1 p(3):

Except when it is the operand of the sizeof operator, the _Alignof operator 1,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.

简单;数组名称可以转换为指向其第一个元素的指针。

由于 a 是一个数组名,它会衰减到指向其第一个元素的指针,该元素是一维数组。它的类型是 int(*)[2]。因为a(衰减后)是一个指向2int数组的指针,所以*a是一个数组2 int。由于这是一个数组类型,即 *a 是第一个一维数组的数组名称,它会衰减为指向第一个元素的指针 (a[0] [0]) 数组对象。所以,它的类型是int *

is this true that b(declared above) and a[0] represent the same thing (both being 1d array and then decay to the pointer to first element in array of type (int*)?

是的 ba[0] 都是 int * 类型(衰减后)。


<子>1。阅读 Keith Thompson 的通信.另请阅读此 answer其中指出:C11 标准的草案指出数组存在另一个异常(exception)情况,即当数组是新的 _Alignof 运算符的操作数时。这是草案中的一个错误,在最终发布的 C11 标准中得到更正; _Alignof 只能应用于带括号的类型名称,不能应用于表达式。

关于c - 为什么取消引用指向整数数组(在二维数组中)的指针会返回(或衰减到)指向第一个元素的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com