繁体   English   中英

指向二维数组 C++ 的数组指针

[英]Array pointer to 2d array c++

我有 N 个二维(列,行)数组。 因此,我试图创建一个大小为 N 的数组指针,每个指针都指向相应的二维数组。 代码就像。

int col = 3,row = 2,N =2;
float blue[][row] = {1,2,3,4,5,6}; // 2d array (for N=1)
float green[][row] = {1,2,3,4,5,6}; // 2d array (for N=2)
float (*arry_ptr[N])[col][row]; // this works

arry_ptr[0]= &blue;  // trying to point the 1st pointer to 1st 2d array
arry_ptr[1]= &green;  // trying to point the 2nd pointer to 2nd 2d array

我知道最后两行代码不合适,它确实会抛出错误。 是否有任何解决方案来增加指针并使其按顺序指向二维数组,而不是像下一行那样。

float (*arry_ptr[N]) ={a,b}  // this works but i can allocate only single 2d array at a time.

首先,C++ 没有变长数组,因此从技术上讲,您的代码是不合法的。 维度需要是编译时常量。

其次,如果是我,我会改用std::array ,并使用类型别名。 像这样的东西:

using array_type = std::array<std::array<float, 2>, 3>;

array_type blue = { ... }
array_type green = { ... }

array_type &array_refs[] = { blue, green };

潜在地,取决于bluegreen数组的用途,我宁愿使用std::pair而不是嵌套数组。 所以像这样:

using array_type = std::array<std::pair<float, float>, 3>;

或者甚至是结构。

现在我在最后两行没有收到任何错误。 我只是将它更改为常量整数,因为我使用的是固定大小.. Dint 监督它。

const int col = 3,row = 2,N =2;
float blue[][row] = {1,2,3,4,5,6}; // 2d array (for N=1)
float green[][row] = {1,2,3,4,5,6}; // 2d array (for N=2)
float (*arry_ptr[N])[col][row]; 
arry_ptr[0]= &blue;  // trying to point the 1st pointer to 1st 2d array
arry_ptr[1]= &green;  // trying to point the 2nd pointer to 2nd 2d array

干杯,LAKSHMI

C++ 是这样标记的,

为此,“ float (*arry_ptr[N]) ={a,b} ”。 我建议使用结构而不是普通数组。

结构 { 浮动 a,b}; // 在此之后你可以做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM