gpt4 book ai didi

c++ - 如何理解取消引用指向数组的指针得到指向元素的指针?

转载 作者:太空狗 更新时间:2023-10-29 21:11:44 25 4
gpt4 key购买 nike

我曾经对这些代码感到困惑

int a[3] = {1,2,3};
int b[2][3] = {...};
int (*p1)[3] = &a; //pointer to array[3]
int (*p2)[3] = b; //same as above
int (*p3)[2][3] = &b; // pointer to array[2][3]

然后我阅读了一些帖子1并了解了数组名称的“奥秘”,包括一些显式和隐式转换。

所以现在我知道 p1 是指向数组的指针,包含 3 个 int 类型的元素。

但是如何理解 *(int (*)[3]) 获取类型 int *

*(int (*)[2][3] 获取类型 int (*)[3] ?

我应该死记硬背吗?


<支持>我读过的帖子:

Is an array name a pointer?

Difference between `a` and `&a` in C++ where `a` is an array

Array to pointer decay and passing multidimensional arrays to functions


PS:我不知道这是不是一个愚蠢的问题。但是在阅读了我上面提到的帖子之后。我仍然对取消引用操作的东西感到有点奇怪。也许这就是我应该牢记并停止挖掘的语言语法的工作方式。 :D

最佳答案

首先,你要明白array-to-pointer decay ,

There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are

例如,a (int [3]) 可能衰减为 int *b (int [2][3]) 可能会衰减到 int (*)[3]

然后

how to understand that *(int (*)[3]) gets type int * or *(int (*)[2][3] gets type int (*)[3] ?

这取决于上下文;更准确地说,给定 int (*)[3] 类型的 p(即指向数组的指针),*p 将得到数组 (int [3]),它可能会衰减到 int *

类似地,给定 int (*)[2][3] 类型的 p*p 将得到数组 int [2][3],可能会衰减为 int (*)[3]

关于c++ - 如何理解取消引用指向数组的指针得到指向元素的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730202/

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