二維數組參數傳遞方法

來源:互聯網
上載者:User
//Array.cpp//二維數組的參數傳遞//2013/6/28#include<iostream>using namespace std;//數組名作為形參void fun1(int iArray[][3]){for(int i=0; i<3; i++){for(int j=0; j<3; j++)cout << iArray[i][j] <<" ";cout << endl;}cout << endl;}//一維數組指標作為形參void fun2(int (*pArray)[3]){/*cout << pArray << endl;cout << &pArray << endl;cout << *pArray << endl;cout << **pArray << endl;cout << *(*(pArray+1)+1) << endl;cout << *pArray+1 << endl;*/for(int i=0; i<3; i++){for(int j=0; j<3; j++)cout << pArray[i][j] << " ";//cout << *(*(pArray+i)+j) <<" ";cout << endl;}cout << endl;}//二維數組引用做形參void fun3(int (&pArray)[3][3]){for(int i=0; i<3; i++){for(int j=0; j<3; j++)cout << *(*(pArray+i)+j) <<" ";cout << endl;}cout << endl;}//二維數組指標做形參void fun4(int (*pArray)[3][3]){for(int i=0; i<3; i++){for(int j=0; j<3; j++)cout << (*pArray)[i][j] <<" ";cout << endl;}cout << endl;}//用雙重指標作為形參void fun5(int **pArray, int m, int n){for(int i=0; i<m; i++){for(int j=0; j<n; j++)cout << *(*(pArray+i)+j) <<" ";cout << endl;}cout << endl;}int main(int argc, char* argv[]){int a[3][3] = {{1,1,1},{2,2,2},{3,3,3}};//數組名做形參fun1(a);//一維數組指標做形參fun2(a);//二維數組引用做形參fun3(a);//指向二維數組指標做形參fun4(&a);int (* aa)[3][3] = &a;for(int i=0; i<3; i++){for(int j=0; j<3; j++)cout << aa[i][j] <<" ";cout << endl;}//用雙重指標作為形參//wrong answer!/*int m = 3;   int n = 3;    int** p = new int[m][n];  */int m = 3;int n = 3;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;}for(int i=0; i<m; i++)for(int j=0; j<n; j++)pArray[i][j] = i+1;*/for(int i=0; i<m; i++)pArray[i] = new int[n]; for(int i=0; i<m; i++)for(int j=0; j<n; j++)pArray[i][j] = i+1;fun5(pArray, m, n);return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.