都知道,數組名和函數名一樣,可以當做指針(普通指針和函數指針)來用。
關於二維數組做為形參聲明和實參傳遞,直接看代碼:
1 #include <iostream> 2 using namespace std; 3 4 /*傳二維數組*/ 5 6 //第1種方式:傳數組,第二維必須標明 7 /*void display(int arr[][4])*/ 8 void display1(int arr[][4],const int irows) 9 { 10 for (int i=0;i<irows;++i) 11 { 12 for(int j=0;j<4;++j) 13 { 14 cout<<arr[i][j]<<" "; //可以采用parr[i][j] 15 } 16 cout<<endl; 17 } 18 cout<<endl; 19 } 20 21 //第2種方式:一重指針,傳數組指針,第二維必須標明 22 /*void display(int (*parr)[4])*/ 23 void display2(int (*parr)[4],const int irows) 24 { 25 for (int i=0;i<irows;++i) 26 { 27 for(int j=0;j<4;++j) 28 { 29 cout<<parr[i][j]<<" "; //可以采用parr[i][j] 30 } 31 cout<<endl; 32 } 33 cout<<endl; 34 } 35 //注意:parr[i]等價於*(parr+i),一維數組和二維數組都適用 36 37 //第3種方式:傳指針,不管是幾維數組都把他看成是指針 38 /*void display3(int *arr)*/ 39 void display3(int *arr,const int irows,const int icols) 40 { 41 for(int i=0;i<irows;++i) 42 { 43 for(int j=0;j<icols;++j) 44 { 45 cout<<*(arr+i*icols+j)<<" "; //注意:(arr+i*icols+j),不是(arr+i*irows+j) 46 } 47 cout<<endl; 48 } 49 cout<<endl; 50 } 51 52 /***************************************************************************/ 53 /* 54 //第2種方式:一重指針,傳數組指針void display(int (*parr)[4]) 55 //缺陷:需要指出第二維大小 56 typedef int parr[4]; 57 void display(parr *p) 58 { 59 int *q=*p; //q指向arr的首元素 60 cout<<*q<<endl; //輸出0 61 } 62 63 typedef int (*parr1)[4]; 64 void display1(parr1 p) 65 { 66 cout<<(*p)[1]<<endl; //輸出1 67 cout<<*p[1]<<endl; //輸出4,[]運算符優先級高 68 } 69 //第3種方式: 70 void display2(int **p) 71 { 72 cout<<*p<<endl; //輸出0 73 cout<<*((int*)p+1+1)<<endl; //輸出2 74 } 75 */ 76 77 int main() 78 { 79 int arr[][4]={0,1,2,3,4,5,6,7,8,9,10,11}; 80 int irows=3; 81 int icols=4; 82 display1(arr,irows); 83 display2(arr,irows); 84 85 //注意(int*)強制轉換.個人理解:相當於將a拉成了一維數組處理。 86 display3((int*)arr,irows,icols); 87 return 0; 88 }
推薦使用第2種方式,簡單明了!
