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++解释任何编译器相关的问题.
C++不再是C的超集.您正在使用C可变长度数组功能,C++没有等效功能.这是非法的C++,坦率地说,这是非常糟糕的做法.使用std::array和模板.这就是他们的目的.因为C阵列太可怕了.