一江春水向東流

          做一個有思想的人,期待與每一位熱愛思考的人交流,您的關(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 閱讀(813) 評論(0)  編輯  收藏 所屬分類: C/C++
          主站蜘蛛池模板: 邳州市| 绥江县| 四川省| 彩票| 云南省| 鄂尔多斯市| 彰化市| 龙山县| 丰顺县| 松潘县| 西贡区| 诸城市| 光山县| 常州市| 芷江| 浦北县| 太仓市| 阿坝县| 无锡市| 九寨沟县| 吉林市| 周至县| 宜春市| 都匀市| 平阳县| 田林县| 江达县| 呼和浩特市| 会理县| 曲水县| 彰化县| 丰县| 嘉善县| 泰兴市| 沽源县| 星座| 勐海县| 江北区| 鄂州市| 兴国县| 阿城市|