#include <iostream>
#include <iomanip>
using namespace std;
//////////method first//////////////////
//直接用二维数组的形式
void fun(int a[3][4])
{
for(int i=0; i<3; ++i)
{
for(int j=0; j<4; ++j)
{
cout<<"a["<<i<<"]["<<j<<"]="<<setw(3)<<a[i][j]<<"\t";
}
cout<<endl;
}
}
/////////////method second//////////////
//用指向数组的指针
void fun1(int (*p)[4])
{
for(int i=0; i<3; ++i)
{
for(int j=0; j<4; ++j)
{
cout<<"p["<<i<<"]["<<j<<"]="<<setw(3)<<p[i][j]<<"\t";
}
cout<<endl;
}
}
///////////method third/////////////////
//形参采用指针,如int* p,而主函数进行特殊操作,使二维数组传值到函数里。
void fun2(int *p)
{
for(int i=0; i<4; ++i)
{
cout<<"p["<<i<<"]="<<setw(3)<<p[i]<<"\t";
}
cout<<endl;
}
////////////method forth////////////////
//用指向指针的指针,如int** p,
void fun3(int **p)
{
for(int i=0; i<3; ++i)
{
for(int j=0; j<4; ++j)
{
cout<<"p["<<i<<"]["<<j<<"] = "<<setw(5)<<p[i][j]<<"\t";
}
cout<<endl;
}
}
int main(int argc,char* argv[])
{
int a[3][4]= {0,1,2,3,4,5,6,7,8,9,10,11};
fun(a);
cout<<endl;
fun1(a);
cout<<endl;
for(int i=0; i<3; ++i)
{
fun2(*(a+i));
}
// fun3(a);
//编译时发生错误。int [][]不能转换为int**
//error: cannot convert ‘int (*)[4]’ to ‘int**’ for argument ‘1’ to ‘void fun3(int**)’
////////////////////////////////////////
int row=3, col=4;
/////////create the 2d dynamic array////
////////////////////////////////////////
int **p=new int *[row];
for(int i=0; i<row; ++i)
{
//用p[i]指向第一个含有col个元素的数组///
p[i]=new int[col];
//p[0]、p[1]、p[2]分别指向一个含有col个元素的数组,
}
////////////////////////////////////////
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
p[i][j]=i*j+j+99;
}
}
cout<<"p="<<p<<" sizeof(p)="<<sizeof(p)<<" *p = "<<*p<<endl;
cout<<"p[0]="<<p[0]<<"\t"<<"*(p+0) = "<<*(p+0)<<endl;
cout<<"p[1]="<<p[1]<<"\t"<<"*(p+1) = "<<*(p+1)<<endl; cout<<"p[2]="<<p[2]<<"\t"<<"*(p+2) = "<<*(p+2)<<endl; int b[2][5]= {0}; cout<<"b="<<b<<"\t"<<"b[0]="<<b[0]<<endl; fun3(p);//////////////////////////////////////////////////删除自己申请的空间//////////// for(int i=0; i<row; ++i) { delete []p[i]; cout<<"delete p["<<i<<"]"<<"\t"; } cout<<endl; delete []p; cout<<"delete p"<<endl;//////////////////////////////////////// cin.get();// return 0;}////[root@yutong array]# g++ -o twodimarraypara twodimarraypara.cpp//[root@yutong array]# ./twodimarraypara //a[0][0]= 0 a[0][1]= 1 a[0][2]= 2 a[0][3]= 3 //a[1][0]= 4 a[1][1]= 5 a[1][2]= 6 a[1][3]= 7 //a[2][0]= 8 a[2][1]= 9 a[2][2]= 10 a[2][3]= 11 ////p[0][0]= 0 p[0][1]= 1 p[0][2]= 2 p[0][3]= 3 //p[1][0]= 4 p[1][1]= 5 p[1][2]= 6 p[1][3]= 7 //p[2][0]= 8 p[2][1]= 9 p[2][2]= 10 p[2][3]= 11 ////p[0]= 0 p[1]= 1 p[2]= 2 p[3]= 3 //p[0]= 4 p[1]= 5 p[2]= 6 p[3]= 7 //p[0]= 8 p[1]= 9 p[2]= 10 p[3]= 11 //p=0x1adf010 sizeof(p)=8 *p = 0x1adf030//p[0]=0x1adf030 *(p+0) = 0x1adf030//p[1]=0x1adf050 *(p+1) = 0x1adf050//p[2]=0x1adf070 *(p+2) = 0x1adf070//b=0x7fff0c6e79f0 b[0]=0x7fff0c6e79f0//p[0][0] = 99 p[0][1] = 100 p[0][2] = 101 p[0][3] = 102 //p[1][0] = 99 p[1][1] = 101 p[1][2] = 103 p[1][3] = 105 //p[2][0] = 99 p[2][1] = 102 p[2][2] = 105 p[2][3] = 108 //delete p[0] delete p[1] delete p[2] //delete p//