[004]多维数组和指针

因为多维数组就是数组的数组,因为我们可以这样来:

int ia[3][4];      // array of size 3, each element is an array of  ints of size 4  
int (*ip)[4] = ia; // ip points to an array of 4 ints  
ip = &ia[2];       // ia[2] is an array of 4 ints  

这样就OK了。*ip 是 int[4] 类型 ——即 ip 是一个指向含有 4 个元素的数组的指针。

需要特别注意的是,加不加括号,是有很大区别的,比如:

int *ip[4]; // array of pointers to int  
int (*ip)[4]; // pointer to an array of 4 ints  

两者是完全不同的两种东西,具体可以参考示例:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int main() 
 6 {
 7     int i = 11;
 8     int j = 12;
 9     int x = 13;
10     int y = 14;
11 
12     int* p1 = &i;
13     int* p2 = &j;
14     int* p3 = &x;
15     int* p4 = &y;
16 
17     int a2[3][4] = {21,22,23,24};
18     int *p5[4] = {p1, p2, p3, p4};
19     int (*p6)[4] = a2;
20     
21     cout << p5 << endl;
22     cout << *p5 << endl;
23     cout << *p5[0] << endl;
24     cout << p6 << endl;
25     cout << *p6 << endl;
26     cout << *p6[0] << endl;
27     cout << *(p6 + 1) << endl;
28 }

输出结果:

svpm-dev# g++ foo.cpp -o foo
svpm-dev# ./foo
0xbfb2084c
0xbfb20868
11
0xbfb2081c
0xbfb2081c
21
0xbfb2082c

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

 除上面的方式外,我们可以使用typedef来简化指向多维数组的指针:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 typedef int int_array[4];
 6 #define ARRAY_SIZE_1 3
 7 #define ARRAY_SIZE_2 4
 8 
 9 int main() 
10 {
11     int a[ARRAY_SIZE_1][ARRAY_SIZE_2] = {11,22,33,44};
12 
13     int_array *ip = a;
14     for (int_array *p = a; p != a + ARRAY_SIZE_1; p++) {
15         for (int *q = *p; q != *p + ARRAY_SIZE_2; q++) {
16             cout << *q << endl;    
17         }
18     }    
19 }

外层的 for 循环首先初始化 p 指向 ia 的第一个内部数组,然后一直循环 到 ia 的三行数据都处理完为止。p++ 使 p 加 1,等效于移动指针使其指向 ia 的下一行(例如:下一个元素)。

内层的 for 循环实际上处理的是存储在内部数组中的 int 型元素值。首先 让 q 指向 p 所指向的数组的第一个元素。对 p 进行解引用获得一个有 4 个int 型元素的数组,通常,使用这个数组时,系统会自动将它转换为指向该数组 第一个元素的指针。在本例中,第一个元素是int型数据,q指向这个整数。系统执行内层的 for循环直到处理完当前 p 指向的内部数组中所有的元素为止。

 得到的结果如下:

svpm-dev# g++ foo.cpp -o foo
svpm-dev# ./foo 
11
22
33
44
0
0
0
0
0
0
0
0
posted @ 2014-03-27 16:51  依然冷月  阅读(186)  评论(0编辑  收藏  举报