如何将多维数组分配给临时变量?

Goo*_*ide 7 c++

我想将一个静态分配的多维数组分配给一个临时变量.请考虑以下示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

基本上我想要做的编译器与参数什么bfoo().但我能提出的唯一可行的解​​决方案是d.有没有那么复杂的方式?

Rob*_*obᵩ 12

cdecl(手册页)是你的朋友:

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]
Run Code Online (Sandbox Code Playgroud)

所以,试试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 9

int[3][2]并且int**是不兼容的类型.你不能把一个扔到另一个.

试试这个:

int (*c)[2];
c = a; //no need to cast 
c[1][1] = 1; //ok
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做(声明和初始化):

int (*c)[2] = a; //no need to cast 
c[1][1] = 1; //ok
Run Code Online (Sandbox Code Playgroud)

规则拇指:

  • 不要在C++中使用c风格的强制转换.使用C++ - 样式转换.如果你使用C++风格的强制转换,编译器会在之前告诉你这个问题(ideone)(不需要运行代码来查看问题):

    prog.cpp:5: error: invalid static_cast from type ‘int (*)[3][2]’ to type ‘int**’
    
    Run Code Online (Sandbox Code Playgroud)

    但是你已经知道,C风格的演员阵容很好(想象).

  • 每当你使用强制转换,甚至是C++风格的强制转换时,如果程序没有按预期工作,你的第一个疑问应该是强制转换.


seh*_*ehe 6

正如您现在可能已经意识到的那样,从其他答案来看,类型a实际上并不等同于int**- 它将jsut 衰减到(通过值返回/传递时).

int (*b)[2] = a; // would solve that
Run Code Online (Sandbox Code Playgroud)

有一种更多的C++方式:

typedef std::array<std::array<int, 2>, 3> M23;

void foo(M23& b)
{
    b[1][1] = 1; 
}

int main()
{
    M23 a = {{1, 2}, {11, 12}, {21, 22}};

    foo(a);

    M23 d = a;
    d[1][1] = 1;
}
Run Code Online (Sandbox Code Playgroud)