转载自博客
二维数组如何作为参数传递?为什么不能直接用二维指针传递?
传递动态数组推荐的方法:强制转换为一维指针,这样一维二维数组可以用同一个函数传入
问题:
尝试int**
做形参,编译错误:int(*)[10]和int**类型不符
void f(int** p){ ; }
int main(){ int a[10][10]; f(a); }
|
三种解决方法
#include using namespace std;
void display1(int arr[][4],const int irows) { for (int i=0;i { for(int j=0;j<4;++j) { cout<" "; } cout<<endl; } cout<<endl; }
void display2(int (*parr)[4],const int irows) { for (int i=0;i { for(int j=0;j<4;++j) { cout<" "; } cout<<endl; } cout<<endl; }
void display3(int *arr,const int irows,const int icols) { for(int i=0;i { for(int j=0;j { cout<<*(arr+i*icols+j)<<" "; } cout<<endl; } cout<<endl; }
int main() { int arr[][4]={0,1,2,3,4,5,6,7,8,9,10,11}; int irows=3; int icols=4; display1(arr,irows); display2(arr,irows);
display3((int*)arr,irows,icols); return 0; }
|