weidagang2046的專欄

          物格而后知致
          隨筆 - 8, 文章 - 409, 評論 - 101, 引用 - 0
          數據加載中……

          C++中動態分配二維數組的方法

          ?

          #include

          #define ?N?4
          typedef?
          int ?p[N]; // 方法一用到

          using ? namespace ?std;

          int ?main()
          {
          ????
          int ?n? = ? 0 ;

          ????
          // 方法一:使用typedef定義一個具有N個元素的數組類型
          ????p? * ptr1;?????? // 定義二維數組??用法與二維數組相同
          ????ptr1? = ? new ?p[N];

          ????
          for ( int ?i? = ? 0 ;?i? < ?N;?i ++ )
          ????????
          for ( int ?j? = ? 0 ;?j? < ?N;?j ++ )
          ????????????ptr1[i][j]?
          = ? ++ n;

          ????cout?
          << ? " 方法一: " ? << ?endl;
          ????
          for (i? = ? 0 ;?i? < ?N;?i ++ )
          ????{
          ????????
          for ( int ?j = 0 ;j? < ?N;?j ++ )
          ????????????cout?
          << ?ptr1[i][j]? << ? " ? " ;
          ????????cout?
          << ?endl;
          ????}
          ????delete[]?ptr1;
          ????cout?
          << ?endl;

          ????
          // ?方法二:使用數組指針
          ???? int ?row? = ?N;????? // 二維數組的行數?
          ???? int ?column? = ?N;?? // 二維數組的列數
          ?????
          ????
          // 分配一個指針數組,其首地址保存在pMatrix中
          ???? int ? ** pMatrix? = ? new ? int * [row];

          ????
          // 為指針數組的每個元素分配一個數組
          ???? for ?( int ?i? = ? 0 ;?i? < ?row;?i ++ )
          ????????pMatrix[i]?
          = ? new ? int [column];

          ????
          // 以上是分配,以下是釋放
          ???? for ?( int ?i? = ? 0 ;?i? < ?row;?i ++ )
          ????????delete?[column]?pMatrix[i];
          ????delete?[row]?pMatrix;

          ????
          // 這些技術可用于構造一個矩陣類

          ????
          return ? 0 ;
          }
          from: http://www.zahui.com/html/9/20062.htm

          posted on 2006-05-16 21:39 weidagang2046 閱讀(858) 評論(0)  編輯  收藏 所屬分類: C/C++

          主站蜘蛛池模板: 湖州市| 札达县| 南和县| 舒城县| 宁津县| 明水县| 建昌县| 天门市| 乌鲁木齐市| 安庆市| 西青区| 呼伦贝尔市| 涪陵区| 同德县| 和政县| 平乡县| 偏关县| 融水| 城步| 德钦县| 个旧市| 柘荣县| 内丘县| 岑溪市| 涟水县| 寻甸| 兴安县| 静乐县| 永城市| 昔阳县| 剑阁县| 平谷区| 商水县| 拉孜县| 长泰县| 桂东县| 东方市| 旺苍县| 荔浦县| 泸水县| 仁怀市|