/
//按照動態二維數組的申請、賦初值、使用、釋放空間五個部分給出代碼,以示參考。
//同時,給出了動態二維數組用作形參和實參的執行個體,方便大家查詢。
#include<iostream>
using namespace std;
//動態二維數組作形參
void display(int ** &p,int row,int col)
{
inti,j;
for(i= 0;i <= row-1;i++)
{
for(j= 0; j <= col-1;j++)
{
cout <<p[i][j]+i+j << "\t";
}
cout << endl;
}
}
//主函數
void main()
{
//-------格式化輸出模板資訊內容------開始------
cout << "程式輸出結果如下所示:" << endl << endl;
cout << "/***************************/" <<endl;
cout << "/* DYNAMICARRAY EXEMPLE */" <<endl;
cout << "/* 唐國峰2011年月日 */" << endl;
cout << "/***************************/" <<endl << endl;
//-------格式化輸出模板資訊內容------結束------
int**p; //這是指向指標的指標
introw,col; //此動態二維數組為“row”行、“col”列
inti,j; //迴圈用變數
//動態二維數組p的申請
cout << "請輸入行數和列數:" << endl << endl;
cin >> row >> col;
cout << endl;
p = newint *[row];
for(int i = 0;i <= row-1;i++)
{
p[i]=new int[col];
}
//為動態二維數組p的元素賦初值
for(i= 0;i <= row-1;i++)
{
for(j= 0; j <= col-1;j++)
{
p[i][j] = 0;
}
}
//動態二維數組p的使用舉例
for(i= 0;i <= row-1;i++)
{
for(j= 0; j <= col-1;j++)
{
cout << p[i][j]<< "\t";
}
cout << endl;
}
cout << endl;
cout << "通過調用函數輸出:" << endl << endl;
//動態二維數組p作為參數
display(p,row,col);
//釋放資源時先將裡面的元素刪掉再刪除p
for(i= 0;i <= row-1;i++)
{
delete[] p[i];
}
deletep;
//-------格式化輸出模板資訊內容------開始------
cout << endl <<endl;
system("pause");
//-------格式化輸出模板資訊內容------結束------
}
程式輸出結果如下所示:
/***************************/
/* DYNAMIC ARRAY EXEMPLE */
/* 唐國峰 2011年10月14日*/
/***************************/
請輸入行數和列數:
2
3