Arrays of pointers, pointers to arrays, and two-dimensional arrays

Let's look at a question:

 1 #include <iostream>
 2 
 3 void main()
 4 {
 5     int n[][3] = {10,20,30,40,50,60};
 6     int (*p)[3];
 7     p=n;
 8     cout << p[0][0] << "," << *(p[0]+1) << "," << (*p)[2] <<endl;
 9     return 0;     
10 }

The output is: 10,20,30

The relationship between the array pointer and the two-dimensional array examined in the previous question, where n is a 2*3 two-dimensional array, p is an array pointer, and the array pointer is a pointer that points to an array. Here p is in (*p), indicating that p is a pointer, the type of the pointer is int(*)[3], and the type pointed to by the pointer is int[3], so the pointer p points to an array of length 3.

At first p points to row 0 of n, because row 0 is an array of length 3. p[0] represents the first address of the 0th line (ie &n[0][0]), p[0]+1 represents the offset of the first address of the 0th line by one address, that is, the address of n[0][1] ( &n[0][1]). So *(p[0]+1) is n[0][1] and the answer is 20.

p==&p[0], means row 0 (because the subscript starts from 0), so *p == p[0], means the first address of row 0, so (*p)[2] is p[ 0][2], which is n[0][2], the answer is 30.

 

Summarize:

Moving directly on p moves rows, and moving on *p moves columns. For example: **(p+1) equals p[1][0], *(*p+1) equals p[0][1].

To be continued~

 

Guess you like

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