二維數組動態分配

int row = 7; /////暫假定行數是2,這個可以在運行時刻決定;
 int column = 6;/////暫假定列數是2,這個可以在運行時刻決定;

 void **ptdhead = NULL; //////////在後面說明爲什麼要用void**類型
 void **ptdBody = NULL;//////////在後面說明爲什麼要用void**類型


 ptdhead = (void **)malloc(sizeof(void*)*row + sizeof(int)*row*column);


 if(!ptdhead)
  return false;

 ptdBody = ptdhead + row ; 


 for(int ncount = 0; ncount < row; ncount++)
 {

  //ptdhead  第ncount維 數組的起始地址 ,
  ptdhead[ncount] = ptdBody + ncount * column;  //相當於首地址加 跳過的(int型)內存個數;malloc時分配內存部分類型以確定

 }
 int **ptdheadRealse;
 ptdheadRealse = (int **)ptdhead;///////////////////強制轉換爲自己程序需要的二維數組元素類型的指針
 ptdhead = NULL;

 for(int i = 0; i < row; i++ )
 {
  for(int j = 0; j< column; j++)
  {
   ptdheadRealse[i][j] = i+j;  ////////進行簡單的初始化;
  }

 }
 for(int i = 0 ; i< row ; ++i)
 {
  for(int j =0 ; j<column ; ++j)
  {
   cout<<ptdheadRealse[i][j] << " ";
  }
  cout <<endl;
 }
 delete []ptdheadRealse;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章