二维数组作为函数参数时,这两种写法有什么区别?
#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
void dfs(int (*a)[10]){
for(int i=0;i<5;i++){
for(int j=0;j<10;j++){
cout<<a[i][j]<<" ";
}
}
}
void dfs2(int a[][10]){
for(int i=0;i<5;i++){
for(int j=0;j<10;j++){
cout<<a[i][j]<<" ";
}
}
}
int main(){
int (*a)[10]=new int[5][10];
for(int i=0;i<5;i++){
for(int j=0;j<10;j++){
a[i][j]=i*j;
}
}
dfs(a);
dfs2(a);
delete []a;
return 0;
}
dfs(int (*a)[10])
和dfs2(int a[][10])
都可以,我想知道什么时候数组非常大,这样会有效率吗?
最佳答案
What is the difference between the two wording when the two-dimensional array is a function parameter?
没有。
这也是为什么如果您尝试为两个函数赋予相同的名称,您会收到重定义错误的原因。
然而,dfs(int (*a)[10])
版本具有更大的教育值(value),因为它告诉你数组不能按值传递;当您尝试这样做时,会传递一个指针,并且大小信息会丢失。你最终得到一个指向 int[10]
的指针对象,它可能是也可能不是整个 int[10]
数组的开头
I want to know when the array very large,Will that be efficient?
因为根本没有区别,所以数组有多大也无关紧要。效率也是一个完全不相关的话题。
在任何情况下,删除所有数组内容并使用 std::vector
.并且不要使用非标准 <bits/stdc++.h>
header ,不要使用 <windows.h>
如果您不需要 Windows API。最后,避免 using namespace std;
.
关于c++ - 二维数组为函数参数时,这两种写法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018146/