在C和C++中传递2d数组的比较

nbb*_*bbk 2 c c++ parameter-passing multidimensional-array

在C.

void foo(int size ,int a[][size])
{
    printf("%d\n", a[0][0]);
}
int main(int argc, char const *argv[])
{
    int a[5][5] = {0};
    foo(5, a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

工作良好

但在C++中也一样

void foo(int size, int a[][size])
{
    cout << a[0][0] << endl;
}
int main(int argc, char const *argv[])
{
    int a[5][5] = {0};
    foo(5, a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不起作用.它给出了两个错误:

 error: use of parameter ‘size’ outside function body
 In function ‘void foo(...)’:
 error: ‘a’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么会这样.还请用C或C++解释任何编译器相关的问题.

Pup*_*ppy 7

C++不再是C的超集.您正在使用C可变长度数组功能,C++没有等效功能.这是非法的C++,坦率地说,这是非常糟糕的做法.使用std::array和模板.这就是他们的目的.因为C阵列太可怕了.

  • "C数组很糟糕" - 至少在C++中(在C语言中,如果没有它们,我们将很难编写程序).另外,`const vector <int>&`也可以很好地完成工作,然后你甚至不需要做模板hackage只是为了从容器中得到一个简单的`.size()`. (3认同)