一江春水向東流

          做一個有思想的人,期待與每一位熱愛思考的人交流,您的關(guān)注是對我最大的支持。

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            44 隨筆 :: 139 文章 :: 81 評論 :: 0 Trackbacks

          一個關(guān)于動態(tài)二維數(shù)組分配內(nèi)存的問題,以前也有做遇見過這樣的,今天在網(wǎng)上參考了一個可以分配任意類型的示例,寫了一個僅分配整型的二維數(shù)組小測試程序,在VC++6.0上測試通過

          int **AllocMatrix ( int iRow, int iCol )
          void FreeMatrix ( int** p )

          示例程序:

          ?

          #include? < stdio.h >
          #include?
          < stdlib.h >
          #include?
          < string .h >
          //////////////////////////////////////////////////////////// //
          void ?FreeMatrix( int ? ** p);
          int ** ?AllocMatrix( int ?iRow,? int ?iCol);

          int ? ** AllocMatrix( int ?iRow,? int ?iCol)
          {
          ????
          int ** ?tdarray? = ?NULL;
          ????
          int * ?tmparray? = ?NULL;
          ????
          int ?i? = ? 0 ;
          ????
          // allocate?pointer?array
          ???? if ( ! (tdarray? = ?( int ** )malloc( sizeof ( char * ) * iRow)))
          ????
          {
          ????????printf(
          " allocate?iRow?wrong\n " );
          ????????exit(
          1 );
          ????}

          ????
          // allocate?actual?array?space
          ???? if ( ! (tmparray? = ?( int * )malloc( sizeof ( int ) * (iRow? * ?iCol))))
          ????
          {
          ????????FreeMatrix(tdarray);
          ????????printf(
          " allocate?iRow?wrong\n " );
          ????????exit(
          1 );
          ????}

          ????
          // initialize?memory
          ????memset(tmparray,? 0x00 ,? sizeof ( int ) * (iRow? * ?iCol));
          ????
          // evaluate?the?pointer?array
          ???? for (i = 0 ;?i < iRow;?i ++ )
          ????????tdarray[i]?
          = ?(tmparray? + ?(i * ?iCol) * sizeof ( int ));
          ????
          return ?tdarray;
          }


          void ?FreeMatrix( int ? ** p)
          {
          ????
          if (p)
          ????
          {
          ????????free(p[
          0 ]);
          ????????free(p);
          ????}

          }


          void ?main( void )
          {
          ????
          int ? ** arr? = ?AllocMatrix( 2 , 2 );
          ????arr[
          1 ][ 1 ]? = ? 1 ;
          ????arr[
          0 ][ 1 ]? = ? 4 ;
          ????printf(
          " %d,?%d?\n " ,arr[ 1 ][ 1 ],?arr[ 0 ][ 1 ]);
          ????FreeMatrix(arr);
          }

          ?

          posted on 2007-04-14 10:01 allic 閱讀(818) 評論(0)  編輯  收藏 所屬分類: C/C++
          主站蜘蛛池模板: 涟源市| 剑川县| 邵东县| 酉阳| 克拉玛依市| 抚远县| 迁安市| 滨州市| 永仁县| 图木舒克市| 吉安县| 贵定县| 神木县| 长治县| 霍山县| 珲春市| 仙居县| 永和县| 方山县| 太白县| 从化市| 富阳市| 江城| 双流县| 烟台市| 邯郸县| 宁夏| 海淀区| 巴楚县| 临邑县| 青海省| 永吉县| 姚安县| 晋城| 新建县| 和平县| 城固县| 格尔木市| 徐水县| 土默特右旗| 淮北市|