指向二维数组的指针
如何让一个指针赋给一个二维数组?
下面的代码将不起作用。
float a1[2][2] = { {0,1},{2,3}};
float a2[3][2] = { {0,1},{2,3},{4,5}};
float a3[4][2] = { {0,1},{2,3},{4,5},{6,7}};
float** b = (float**)a1;
//float** b = (float**)a2;
//float** b = (float**)a3;
cout << b[0][0] << b[0][1] << b[1][0] << b[1][1] << endl;
How can I let a pointer assigned with a two dimensional array?
The following code won't work.
float a1[2][2] = { {0,1},{2,3}};
float a2[3][2] = { {0,1},{2,3},{4,5}};
float a3[4][2] = { {0,1},{2,3},{4,5},{6,7}};
float** b = (float**)a1;
//float** b = (float**)a2;
//float** b = (float**)a3;
cout << b[0][0] << b[0][1] << b[1][0] << b[1][1] << endl;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
a1
无法转换为float**
。所以你的做法是非法的,不会产生预期的结果。试试这个:
这会起作用,因为
float[M][2]
类型的二维数组可以转换为float (*)[2]
。它们与M
的任何值兼容。作为一般规则,对于
MType[M][N]
可以转换为Type (*)[N]
代码>和<代码>N。a1
is not convertible tofloat**
. So what you're doing is illegal, and wouldn't produce the desired result.Try this:
This will work because two dimensional array of type
float[M][2]
can convert tofloat (*)[2]
. They're compatible for any value ofM
.As a general rule,
Type[M][N]
can convert toType (*)[N]
for any non-negative integral value ofM
andN
.如果所有数组的最终维度为 2(如示例中所示),那么您可以执行以下操作
If all your arrays will have final dimension 2 (as in your examples), then you can do
你这样做的方式在 C++ 中是不合法的。您需要有一个指针数组。
The way you do this is not legit in c++. You need to have an array of pointers.
这里的问题是编译器不知道 b 的维度。当您将 a1 转换为浮点数**时,信息会丢失。转换本身仍然有效,但不能用 b[][] 引用数组。
The problem here is that the dimensions of b are not known to the compiler. The information gets lost when you cast a1 to a float**. The conversion itself is still valid, but you cannot reference the array with b[][].
你可以明确地做到这一点:
You can do it explicitly:
尝试将 b 直接等于 a1,这意味着指针 b 指向指针 a1 指向的同一内存位置,它们现在携带相同的内存引用,您应该能够遍历该数组。
Try assigning b to be directly equals to a1, that's mean that the pointer b is pointing to the same memory location that pointer a1 is pointing at, they carry the same memory reference now, and you should be able to walk through the array.