(原創) 2 dim array該如何完全使用pointer存取? (C/C++) (C)
array和pointer互換,其實只有一個公式:a[i] = *(a+i),任何維度都適用這個公式,以下範例demo 2 dim array該如何使用pointer存取。
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : TwoDimArrayByPointer.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to access two dimension array by pointer
7Release : 12/12/2006 1.0
8*/
9
10#include <iostream>
11
12using namespace std;
13
14int main() {
15 const int SIZEX = 3;
16 const int SIZEY = 3;
17
18 int yokoi[SIZEX][SIZEY];
19 for(int i = 0; i != SIZEX; ++i) {
20 for (int j = 0; j != SIZEY; ++j) {
21 yokoi[i][j] = i + j*2;
22 }
23 }
24
25
26 for(int i = 0; i != SIZEX; ++i) {
27 for (int j = 0; j != SIZEY; ++j) {
28 cout << yokoi[i][j] << " ";
29 }
30 cout << endl;
31 }
32
33 cout << endl;
34
35 for(int i = 0; i != SIZEX; ++i) {
36 for (int j = 0; j != SIZEY; ++j) {
37 cout << yokoi[i][j] << " ";
38 cout << *(yokoi[i] + j) << " ";
39 cout << *(*(yokoi + i) + j)<< " ";
40 cout << *(*yokoi + i * SIZEX + j) << " ";
41 }
42 cout << endl;
43 }
44
45 return 0;
46}
37上是正統使用array的寫法,最乾淨也最容易閱讀。
38行是一半array,一半pointer的寫法,有一個觀念需要澄清,2 dim array在C/C++事實上是array of array,也就是C#的jagged array,第一個array是2 dim array的第一個column,第一個array的每個element再存放2 dim array的每一個row,而每個row也是個array,所以yokoi事實上是第一個array的位址,而yokoi[0]為第一個row這個array的位址,yokoi[1]為第二個row這個array的位址,以此類推...,所以yokoi[i] + j為每個element實際的位址,最後再用* dereference取值。
39行寫法完全用pointer,由於yokoi是第一個array的位址,所以*(yokoi + i) 相當於 yokoi[i],再加上j後即為每個element實際的位址。
40行也是完全用pointer,但卻是另外一種觀念,在C/C++中雖然表面上是2 dim array,但骨子裡卻仍是1 dim array,若你觀察2 dim array的位址,會發現其記憶體是連續的,根本就是1 dim array,所以40的寫法是用1 dim array的方式去存取,由於yokoi是第一個陣列,若直接做加減,位址會一次加一列,所以必須在dereference一次:*yokoi,取的第二個array的位址,如此位址相加後,才是一次一個int,最後再dereference取值。
該用哪種寫法呢?
若用array subscripting寫法,則建議第37行的寫法,這種寫法和其他語言類似,一目了然。
若用pointer寫法,則建議39行的寫法,這也是標準的寫法,若對array和pointer概念夠清楚,其實這種寫法也是一目了然。