動態二維數組的申請、賦初值、使用、釋放空間

來源:互聯網
上載者:User

/

 

//按照動態二維數組的申請、賦初值、使用、釋放空間五個部分給出代碼,以示參考。

//同時,給出了動態二維數組用作形參和實參的執行個體,方便大家查詢。

 

#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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.