[C/C++] Array & Pointer

 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 }            

Analysis:

1. The difference between int a[3] and int *pa = new int[3]:

  sizeof is an operator, not a function, so the size is determined at compile time. For a fixed-length array, the value of sizeof is the length of the array * type bytes, while for a pointer, the value of sizeof is determined by the machine word length.

 

2. The difference between int *c[4] and int (*d)[4]:

  The above definition involves two operators: "*" (reference), "[]" (subscript), and the precedence of "[]" is greater than that of "*".

 

  int *c[4]: "[]" has high priority, so it is first an array of length 4, that is, c[4]; the remaining int * is used as a supplement, indicating that each element of the array points to a pointer of type int. So it's an array of pointers .

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 }

output result

1

2 3

 

  int (*d)[4]: (*d) indicates that it is a pointer first; the remaining int[4] is supplemented, indicating that the pointer d points to an array of length 4. So it is a pointer to a 1D array .

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] are both one-dimensional arrays of length 4, here d = a; or d = a + 1; is also syntactically correct 
5      for ( int i = 0 ; i < 2 ; i++ ) {
 6          for ( intj = 0 ; j < 4 ; j++ ) {
 7              cout << (*(d + i))[j] << "  " ;     // no less than 8 parentheses 
        }
 9          cout << endl;
 10     }
 11 return 0 ;
 12 }        

output result

1 2 3 4

5 6 7 8

 

3. Whether it is a first-level pointer or a second-level pointer, it occupies 4 bytes.

 

above

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325344848&siteId=291194637