指向2D数组的指针的类型是什么? [英] What is the type of a pointer to a 2D array?

查看:46
本文介绍了指向2D数组的指针的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下内容不正确:

I know that the following is not correct:

int arr[2][3] = {}; //some array initialization here
int** ptr;
ptr = arr;

但是我很惊讶以下几行有效

But I am quite surprised that the following lines actually work

int arr[2][3] = {}; //some array initialization here
auto ptr = arr;
int another_arr[2][3] = {}; //some array initialization here
ptr = another_arr;

谁能解释第二个代码块中分配给ptr的类型是什么,以及在下面发生了什么?

Can anyone possibly explain what is the type assigned to ptr in the second block of code, and what happened underneath?

推荐答案

好吧,几乎在所有地方使用数组时,数组都会衰减到指针.所以自然地,您的代码片段中也会发生衰减.

Well, arrays decay to pointers when used practically everywhere. So naturally there's decay going on in your code snippet too.

但是只有最外面的"数组维会衰减到指针.由于数组是行优先的,因此最终将 int(*)[3] 作为指针类型,它是指向一维数组而不是二维数组的指针.它指向第一个行".

But it's only the "outer-most" array dimension that decays to a pointer. Since arrays are row-major, you end up with int (*)[3] as the pointer type, which is a pointer to a one-dimensional array, not a two dimensional array. It points to the first "row".

如果您想让 ptr 的推论成为指向数组的指针,请使用address-of运算符:

If you want ptr's deduction to be a pointer to the array instead, then use the address-of operator:

auto ptr = &arr;

现在 ptr int(*)[2] [3] .

这篇关于指向2D数组的指针的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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