//二維數組傳參問題示例 #include<iostream> using namespace std; //方法1:傳遞數組,注意第二維必須標明 void fun1(int arr[][3],int iRows) { for(int i=0;i<iRows;i++) { for(int j=0;j<3;j++) { cout<<arr[i][j]<<" "; } cout<<endl; } cout<<endl; } //方法二:一重指針 void fun2(int (*arr)[3],int iRows) { for(int i=0;i<iRows;i++) { for(int j=0;j<3;j++) { cout<<arr[i][j]<<" "; } cout<<endl; } cout<<endl; } //方法三:指針傳遞,不管是幾維數組都把他看成是指針, void fun3(int*arr,int iRows,int iCols) { for(int i=0;i<iRows;i++) { for(int j=0;j<3;j++) { cout<<*(arr+i*iRows+j)<<" "; } cout<<endl; } cout<<endl; } int main() { int a[2][3]={{1,2,3},{4,5,6}}; fun1(a,2); cout<<endl; fun2(a,2); cout<<endl; //此處必須進行強制類型轉換,因為a是二維數組,而需要傳入的是指針 //所以必須強制轉換成指針,如果a是一維數組則不必進行強制類型轉換 //為什么一維數組不用強制轉換而二維數組必須轉換,此問題還沒解決,期待大牛! fun3((int*)a,2,3); cout<<endl; }
用雙重指針int**作為形參,接受二維數組實參嗎?答案是肯定的,但是又局限性。用雙重指針作為形參,那么相應的實參也要是一個雙重指針。事實上,這個雙重指針其實指向一個元素是指針的數組,雙重指針的聲明方式,很適合傳遞動態創建的二維數組。怎么動態創建一個二維數組?如下程序:
- int main()
- {
- int m = 10;
- int n = 10;
- int** p = new int[m][n];
- }
會發現編譯不通過,第二個維度長度必須為常量。那么怎么聲明一個兩個維度都能動態指定的二維數組呢?看下面:
- void func5(int** pArray, int m, int n)
- {
- }
- #include <ctime>
- int main()
- {
- int m = 10;
- int n = 10;
- int** pArray = new int* [m];
- pArray[0] = new int[m * n]; // 分配連續內存
- // 用pArray[1][0]無法尋址,還需指定下標尋址方式
- for(int i = 1; i < m; i++)
- {
- pArray[i] = pArray[i-1] + n;
- }
- func5(pArray, m, n);
- }
這里為二維數組申請了一段連續的內存,然后給每一個元素指定尋址方式(也可以為每一個元素分別申請內存,就不必指定尋址方式了),最后將雙重指針作為實參傳遞給func5。這里func5多了兩個形參,是二維數組的維度,也可以不聲明這兩個形參,但是為了安全嘛,還是指定的好。最后編譯,運行,一切OK。總結一下,上面的代碼其實是實現了參數傳遞動態創建的二維數組。