【C/C++】数组 & 指针

 1 int main() {
 2     int a[3];                // 12
 3     int *pa = new int[3];    // 4
 4     int b[3][4];             // 48
 5     int *c[4];               // 16
 6     int (*d)[4];             // 4
 7     int **e;                 // 4
 8     int **f[3];              // 12
 9     int **g[3][4];           // 48
10     cout << sizeof(a) << endl;
11     cout << sizeof(pa) << endl;
12     cout << sizeof(b) << endl;
13     cout << sizeof(c) << endl;
14     cout << sizeof(d) << endl;
15     cout << sizeof(e) << endl;
16     cout << sizeof(f) << endl;
17     cout << sizeof(g) << endl;
18     return 0;
19 }            

辨析:

1、int a[3] 和 int *pa = new int[3] 的区别:

  sizeof 是一个运算符,不是函数,所以是在编译的时候确定大小的。对于确定长度的数组,sizeof 的值为数组长度*类型字节,而对于指针,sizeof 的值由机器字长决定。

2、int *c[4] 和 int (*d)[4] 的区别:

  以上定义涉及两个运算符:“*”(引用)、“[]”(下标),“[]”的优先级大于“*”的优先级。

  int *c[4]:“[]”的优先级高,所以它首先是个长度为 4 的数组,即 c[4];剩下的 int * 作为补充,说明该数组的每一个元素为指向一个 int 类型的指针。因此它是一个指针数组

1 int main() {
2     int a = 1;
3     int b[2] = {2, 3};
4     int *c[4] = {&a, b};
5     cout << *c[0] << endl;
6     cout << c[1][0] << " " << c[1][1] << endl;
7     return 0;
8 }

输出结果

1

2 3

  int (*d)[4]:(*d) 表明它首先是个指针;剩下的 int [4] 作为补充,说明指针 d 指向一个长度为 4 的数组。因此它是一个指向一维数组的指针

 1 int main() {
 2     int a[2][4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 3     int (*d)[4];
 4     d = &a[0];    // a[0]、a[1]都是长度为4的一维数组,这里写 d = a; 或 d = a + 1; 语法上也正确
 5     for (int i = 0; i < 2; i++) {
 6         for (int j = 0; j < 4; j++) {
 7             cout << (*(d + i))[j] << " ";    // 括号不能少
 8         }
 9         cout << endl;
10     }
11     return 0;
12 }

输出结果

1 2 3 4

5 6 7 8

3、不论是一级指针还是二级指针,都占 4 字节。

以上

猜你喜欢

转载自www.cnblogs.com/wayne793377164/p/8990116.html