指向二维数组的指针

发布于 2024-11-28 18:19:56 字数 358 浏览 1 评论 0原文

如何让一个指针赋给一个二维数组?

下面的代码将不起作用。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

沙沙粒小 2024-12-05 18:19:56

a1 无法转换为 float**。所以你的做法是非法的,不会产生预期的结果。

试试这个:

float (*b)[2] = a1;
cout << b[0][0] << b[0][1] <<  b[1][0] <<  b[1][1] << endl;

这会起作用,因为 float[M][2] 类型的二维数组可以转换为 float (*)[2]。它们与 M 的任何值兼容。

作为一般规则,对于 MType[M][N] 可以转换为 Type (*)[N]代码>和<代码>N。

a1 is not convertible to float**. So what you're doing is illegal, and wouldn't produce the desired result.

Try this:

float (*b)[2] = a1;
cout << b[0][0] << b[0][1] <<  b[1][0] <<  b[1][1] << endl;

This will work because two dimensional array of type float[M][2] can convert to float (*)[2]. They're compatible for any value of M.

As a general rule, Type[M][N] can convert to Type (*)[N] for any non-negative integral value of M and N.

谜泪 2024-12-05 18:19:56

如果所有数组的最终维度为 2(如示例中所示),那么您可以执行以下操作

float (*b)[2] = a1; // Or a2 or a3

If all your arrays will have final dimension 2 (as in your examples), then you can do

float (*b)[2] = a1; // Or a2 or a3
花开柳相依 2024-12-05 18:19:56

你这样做的方式在 C++ 中是不合法的。您需要有一个指针数组。

The way you do this is not legit in c++. You need to have an array of pointers.

玻璃人 2024-12-05 18:19:56

这里的问题是编译器不知道 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[][].

悸初 2024-12-05 18:19:56

你可以明确地做到这一点:

float a1[2][2] = { {0,1},{2,3}};
float* fp[2] = { a1[0], a1[1] };
// Or
float (*fp)[2] = a1;

You can do it explicitly:

float a1[2][2] = { {0,1},{2,3}};
float* fp[2] = { a1[0], a1[1] };
// Or
float (*fp)[2] = a1;
笑,眼淚并存 2024-12-05 18:19:56

尝试将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文