指向固定大小的数组的指针数组

编程入门 行业动态 更新时间:2024-10-25 06:22:55
本文介绍了指向固定大小的数组的指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图将两个固定大小的数组分配给指向它们的指针数组,但是编译器警告我,我不明白为什么.

I tried to assign two fixed-size arrays to an array of pointers to them, but the compiler warns me and I don't understand why.

int A[5][5]; int B[5][5]; int*** C = {&A, &B};

此代码编译时显示以下警告:

This code compiles with the following warning:

警告:从不兼容的指针类型初始化(默认情况下启用)

warning: initialization from incompatible pointer type [enabled by default]

如果我运行代码,它将引发分段错误.但是,如果我动态分配A和B,它就可以正常工作. 这是为什么?

If I run the code, it will raise a segmentation fault. However, if I dynamically allocate A and B, it works just fine. Why is this?

推荐答案

如果您想要一个符合现有A和B声明的C声明,则需要这样做:

If you want a declaration of C that fits the existing declarations of A and B you need to do it like this:

int A[5][5]; int B[5][5]; int (*C[])[5][5] = {&A, &B};

C的类型读取为" C是指向int [5][5]数组的指针的数组".由于无法分配整个数组,因此需要分配一个指向该数组的指针.

The type of C is read as "C is an array of pointers to int [5][5] arrays". Since you can't assign an entire array, you need to assign a pointer to the array.

使用此声明,(*C[0])[1][2]正在访问与A[1][2]相同的内存位置.

With this declaration, (*C[0])[1][2] is accessing the same memory location as A[1][2].

如果您想要更简洁的语法,例如C[0][1][2],则需要执行其他人所说的并动态分配内存:

If you want cleaner syntax like C[0][1][2], then you would need to do what others have stated and allocate the memory dynamically:

int **A; int **B; // allocate memory for A and each A[i] // allocate memory for B and each B[i] int **C[] = {A, B};

您也可以使用来自莫斯科的Vlad建议的语法来做到这一点:

You could also do this using the syntax suggested by Vlad from Moscow:

int A[5][5]; int B[5][5]; int (*C[])[5] = {A, B};

该C声明被读为" C是指向int [5]数组的指针的数组".在这种情况下,C的每个数组元素都为int (*)[5]类型,而int [5][5]类型的数组可以衰减为该类型.

This declaration of C is read as "C is an array of pointers to int [5] arrays". In this case, each array element of C is of type int (*)[5], and array of type int [5][5] can decay to this type.

现在,您可以使用C[0][1][2]访问与A[1][2]相同的内存位置.

Now, you can use C[0][1][2] to access the same memory location as A[1][2].

此逻辑也可以扩展到更高的维度:

This logic can be expanded to higher dimensions as well:

int A[5][5][3]; int B[5][5][3]; int (*C[])[5][3] = {A, B};

更多推荐

指向固定大小的数组的指针数组

本文发布于:2023-07-29 00:50:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   大小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!