二维数组是双指针吗? [英] Is 2d array a double pointer?

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

问题描述

int main()
{
    matrix[2][4] = {{11,22,33,99},{44,55,66,110}};
    int **ptr = (int**)matrix;
    printf("%d%d",**matrix,*ptr);
}

但是当一个二维数组作为参数传递时,它被类型转换为 (*matrix)[2] ..编译器将这个数组存储为什么类型......它是存储为二维数组还是双指针或指向数组的指针..如果它存储为数组,它如何在不同情况下进行不同的解释.请帮我理解.

But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] .. what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.

推荐答案

二维数组是双指针吗?

Is 2d array a double pointer?

没有.你程序的这一行不正确:

No. This line of your program is incorrect:

int **ptr = (int**)matrix;

这个答案涉及同一主题

如果你想具体了解多维数组是如何实现的:

If you want concrete image how multidimensional arrays are implemented:

多维数组的规则与普通数组的规则没有区别,只是将内部"数组类型替换为元素类型.数组项直接依次存储在内存中:

The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:

matrix: 11 22 33 99 44 55 66 110
        -----------               the first element of matrix
                    ------------  the second element of matrix

因此,要寻址元素matrix[x][y],取矩阵的基地址+x*4+y(4是内部数组大小).

Therefore, to address element matrix[x][y], you take the base address of matrix + x*4 + y (4 is the inner array size).

当数组传递给函数时,它们会衰减为指向其第一个元素的指针.正如您所注意到的,这将是 int (*)[4].类型中的 4 然后会告诉编译器内部类型的大小,这就是它起作用的原因.对类似的指针进行指针运算时,编译器会加上元素大小的倍数,所以对于matrix_ptr[x][y],你得到matrix_ptr + x*4 + y,和上面的完全一样.

When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]. The 4 in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y], you get matrix_ptr + x*4 + y, which is exactly the same as above.

演员 ptr=(int**)matrix 因此是不正确的.这一次, *ptr 表示存储在矩阵地址处的指针值,但没有.其次,在程序内存中的任何地方都没有指向 matrix[1] 的指针.

The cast ptr=(int**)matrix is therefore incorrect. For once, *ptr would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1] anywhere in the memory of the program.

注意:本文中的计算假设 sizeof(int)==1,以避免不必要的复杂性.

Note: the calculations in this post assume sizeof(int)==1, to avoid unnecessary complexity.

这篇关于二维数组是双指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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