在介紹簡單的二維陣列設定初始值之後,

接下來探討一些簡單的二維陣列與指標,

實做方式有很多種,這裡介紹的是用整數指標去存取二維陣列

有幾點必需要注意的..

(1) 若宣告為 int a[m][n]
     再設一個整數指標指向二維陣列a:
      int *ptr = &a[0][0];

(2) 要存取 a[i][j], 則使用
      *(ptr+i*n+j) ;
     換句話說 ,  *(ptr+i*n+j)  就同等於 a[i][j]

(3) 為什麼要用指標代替陣列呢?
     當然用指標存取會顯得麻煩些,
     但 - 用指標存取會快些,同時程式突然當掉機率也小些...

以下程式碼僅供參考

// =================================
// FileName: TwoDimPtr.cpp
// Author: Edison.Shih.

#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
      int i=0, j=0;
      int row_cnt = 0;
      int col_cnt = 0;

      // 宣告與初始一維.二維陣列
      int a1[3] = {1,2,3};
      int a2[2][3] = { {1,2,3},
                              {4,5,6}
                                          };
     
      row_cnt = sizeof(a2)/sizeof(a2[0]);
      col_cnt = sizeof(a2[0])/sizeof(a2[0][0]);
     
      // 一維陣列與指標
      cout << "one dim:" << endl;
      int *ptr = &a1[0];
      for(i=0; i<3; i++) cout << *(ptr+i) << " ";
      cout << endl << endl;
     
      // 二維陣列與指標
      cout << "two dim:" << endl;
      ptr = &a2[0][0];
      for(i=0; i<row_cnt; i++){
            for(j=0; j<col_cnt; j++) cout << *(ptr+i*col_cnt+j) << " ";
            cout << endl;
      }

      return 0;
}
// =================================

執行結果如下

one dim:
1 2 3

two dim:
1 2 3
4 5 6

// =================================

arrow
arrow
    全站熱搜

    Edison 發表在 痞客邦 留言(2) 人氣()