1
int value = 5; 
int a[ ] = {2,4,6,9,3,5,7}; 
int *q1 = &value; 
int *q2 = a; 
int *q3 = &a[2]; 
int *p[ ] = { q1, q2, q3 }; 

cout<<p[0][0]<<" " <<p[1][1] <<" " <<p[2][3];

answer is 5 4 5.

May I know that how can I get the answer? I'm confused, thanks for guides!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2611244
  • 51
  • 2
  • 4
  • 9

1 Answers1

4

What you need to know:

  1. An expression a[i] is equivalent to *(a + i), and so an expression a[i][j] is equivalent to *(a[i] + j) that is also equivalent to *(*(a + i) + j).

  2. When you assign array name to a pointer it decays into address of first element address for example:

     int a[ ] = {2, 4, 6, 9, 3, 5, 7}; 
     int *q2 = a;  
    

    Now q2 points to first element that is a[0].

    Read also some exceptions where array name not decaying into a pointer to first element? ably answered by @H2CO3.   

  3. When you add i to a pointer p it start pointing to ith element location from p address. So suppose id p points to second element in array p + 3 points to fifth element in array (similarly subtraction works in opposite direction). Read 10.2 Pointers and Arrays; Pointer Arithmetic and Pointer Arithmetic.

To answer your question: In Code:

int value = 5; 
//          0  1  2  3  4  5  6 
int a[ ] = {2, 4, 6, 9, 3, 5, 7}; 
int *q1 = &value; 
int *q2 = a;  // address of array a decays into address of first element
int *q3 = &a[2]; 
int *p[ ] = { q1, q2, q3 };  // can be written as below

last line equivalent to:

int *p [] = { &value, a, &a[2]};

Pointer P is an array of pointer to int so p[i] means address, and p[i][j] is int value:

 p[0][0] == *(p[0] + 0) == *(&value + 0) ==  *&value == value  == 5
 p[1][1] == *(p[1] + 0) == *(a + 1) ==  a[1] == 4
 p[2][3] == *(p[2] + 3) == *(&a[2] + 3) 
           //            0  1  2  3  4  5  6 
           //int a[ ] = {2, 4, 6, 9, 3, 5, 7};
           //                    +1 +1 +1
                        == that is value at 3rd location from index 2
                        == a[5]  == 5
// When you add 1 to an address pointer start pointing to next location

@From Dyp: You can understand last expression as:
Expression *(&a[2] + 3) is defined as *(&*(a+2) + 3), which is equal to *(a+5) and the same as a[5]:

 p[2][3] == *(p[2] + 3) == *(&a[2] + 3) == *(&*(a+2) + 3) 
                                        == *((a+2) + 3)
                                        == *(a + 2 + 3)
                                        == *(a + 5) == a[5] == 5

Hope this help.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208