Sunday 3 April 2016

Pointer :C/C++ brush up

int a;
&a                                  address of a
int *p                              capable of storing address of a non pointer
int **p                            capable of storing address of a pointer .this is also known as double pointer

Let us consider and code to understand above concept better


  1. int *p;
  2. int **c;
  3. int a[ ]={1,2,3,4};
  4. *p=a;                      //*p gives value of a[0] i.e 1                                  
  5. **c=&p;                 //c gives value(pointer stores address in its value) of p pointer 2293552
  6.                                //**c gives address of p pointer
  7.                                //*c --check yourself ! I don't Know
  8. printf("%u",p);       //p gives address of a[0] 2293548  
  9. *(a+i) is same as a[i]              
  10. (a+i) is same as a or &a
Notations for 2-D array


  1. //  in 1-d array you write int*p=a; but if a is 2-d array then this statement will give error
  2. int b[2][3]={ {1,2,3} , {3,4,2} };  //here b[0] occupy 8 bytes as 2 x {[0],[1],[2],[4]}=2 x 4=8 

  3. int(*p)[3]=b;       <--correct statement
  4. printf("%d",*b); / printf("%d",b[0]); / printf("%d",&b[0][0]); / printf("%d",b);printf("%d",&b[0]); <--means an address of first element.first row b[0][0]
  5. .
  6. printf("%d",*(*b+1)); <--means value at b[0][1] which is 2
  7. .
  8. Concluded: b[i][j]=*(b[i]+j) / *(*(b+i)+j) 
  9. .
  10. .

  11. printf("%d",b+1);/printf("%d",*(b+1));/printf("%d",b[1]);/printf("%d",&b[1][0]);<--means 
  12.                                                 //address of first element second row b[1][0]

  13. printf("%d",*(b+1)+2);.  //means address of b[1][2]





Notations for 3-D array




  1. int c[3][2][2]={     {{2,5},{7,9}}  , {{3,4},{6,1}} , {{0,8},{11,13}}  };
  2.  c[i][j][k]
  3. printf("%d",*c)  / printf("%d",c[0])  / printf("%d",c[0][0]) <--addr of c[0][0][0]

  4.  printf("%d",*(c[1]+1))/ / printf("%d",c[1][1])/ / printf("%d",&c[1][1][0])<--addr of c[1][1][0]
  5.                                        printf("%d",*(c[0][1]+1)) <--value of c[0][1][1];
  6. i.e c[i][j][k]= / printf("%d",*(c[i][j]+k));/printf("%d",*(*(c[i]+j)+k));/printf("%d",*(*(*(c+i)+j)+k));





Do you Know ?


  • loop pointer move by size of data type
  • scanf has &a to take value
  • printf has just a to print value
  • in array no need to write & while passing address




type specifier for printing a address--%u



No comments:

Post a Comment