Recently, the written examination often encountered this p + 1 problem, which is as clear as C ++ Primer: There is no multi-dimensional array in C/C ++, only elements are arrays of arrays.
- The distance between a pointer and 1 movement: the distance between a pointer and 1 movement is the size of the elements it points to in the memory.
- So the pointer pointing to the int goes through four bytes by adding 1;
- The pointer pointing to int [N] goes through N * 4 bytes plus 1;
- And so on.
- * P is the type of the element pointed to by P, so * p + 1 is the result of the type of the element pointed to by P.
- Array name a is a pointer to its element type.
- The address & A for the array name is a pointer. The distance between the pointer and 1 is the number of elements multiplied by the size of each element.
Template <typename T> int F (t p) {return int (p + 1)-int (p);} template <typename T> int get (t p) {return * (int *) (p + 1)-1);} int main (void) {int A [2] [2] [2] ={{ 1, 2}, {3, 4 }},{ 5, 6}, {7, 8 }}; int * P; INT (* P1) [2]; int (* P2) [2] [2]; P = A [0] [0]; P1 = A [0]; p2 = A; print (f (p); // 4 print (f (P1); // 4*2 = 8 print (f (P2 )); // 4*2*2 = 16 print (f (* p); // 1 print (f (* P1 )); // 4 print (f (* P2); // 4*2 = 8 print (get (& )); // 8 = A [1] [1] [1] print (get (& A [0]); // 4 = A [0] [1] [1] print (get (& A [0] [0]); // 2 = A [0] [0] [1] Return 0 ;}