如何将多维数组分配给临时变量? [英] How to assign a multi-dimensional array to a temporary variable?
本文介绍了如何将多维数组分配给临时变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个静态分配的多维数组分配给一个临时变量。考虑以下示例:
I want to assign a statically allocated, multi-dimensional array to a temporary variable. Consider the following example:
void foo(int b[3][2])
{
b[1][1] = 1; // no segmentation fault
}
int main()
{
int a[3][2] = {{1, 2}, {11, 12}, {21, 22}};
foo(a);
int** c;
c = (int**)&a;
c[1][1] = 1; // segmentation fault on execution
int* d[3];
d[0] = (int*)&(a[0]);
d[1] = (int*)&(a[1]);
d[2] = (int*)&(a[2]);
d[1][1] = 1; // no segmentation fault
return 0;
}
基本上我想做编译器对参数 b
of foo()
。但是我唯一可以想到的工作解决方案是 d
。有没有更简单的方法?
Basically I want to do what the compiler does with the parameter b
of foo()
. But the only working solution I could come up with is d
. Is there no less complicated way?
推荐答案
cdecl> explain int b[3][2]
declare b as array 3 of array 2 of int
cdecl> declare b as pointer to array 2 of int
int (*b)[2]
所以,尝试这样:
void foo(int b[3][2])
{
b[1][1] = 1; // no segmentation fault
}
int main()
{
int a[3][2] = {{1, 2}, {11, 12}, {21, 22}};
foo(a);
int (*b)[2] = a;
b[1][1] = 1;
return 0;
}
这篇关于如何将多维数组分配给临时变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文