Pointer and multi-dimensional array

Source: Internet
Author: User

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.
  1. So the pointer pointing to the int goes through four bytes by adding 1;
  2. The pointer pointing to int [N] goes through N * 4 bytes plus 1;
  3. 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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.