Please open the menu to show more

Tuesday, August 22, 2017

One of the most important and frequently asked interview question on pointers

Question: Hey, can you explain the "pointer to a constant" and a "constant pointer".
               Also explain the combo of these two.

Note: Please copy and paste this code in any IDE related to C or C++.
(I have used Dev C++)

Detailed Explanation: 

----------------------------------------------------------------------------  

#include<stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = 1;

// 'p' is a pointer to constant
// means the value which is pointed by pointer 'p' can't be modified
// but address stored inside pointer 'p' can be modified
// so, lets create a pointer to constant 'p' and store address of 'a' inside it
int const *p = &a;

// lets store the address of variable 'b' inside pointer 'p'
p = &b;

// lets modify the value pointed by pointer 'p'
// as we know we can't change the value pointed by pointer 'p'
// this statement will raise a compilation error
*p = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// 'q' is a constant pointer 
// means the address which is stored inside pointer 'q' can't be modified
// so, lets create a constant pointer 'q' and store address of 'a' inside it
int *const q = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'q'
// this statemnt will raise a compilation error
q = &b;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// this statement works fine since value pointed by pointer 'q' can be changed
*q = 100;

// 'r' is a constant pointer as well as pointer to constant 
// means the address which is stored inside pointer 'r' can't be changed
// also the value pointed by pointer 'r' can't be changed
// so, lets create a constant pointer to constant 'r' and store address of 'a'
        // inside it
const int *const r = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'r'
// this statemnt will raise a compilation error
r = &a;   // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

// lets modify the value pointed by pointer 'r'
// as we know we can't change the value pointed by pointer 'r'
// this statemnt will raise a compilation error
*r = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

      return 0;
}

----------------------------------------------------------------------------    

2 comments:

  1. Now i am able to answer this question ..... Thanks a lot for uploading this ans.

    ReplyDelete
  2. Thank you sir keep sharing these questions

    ReplyDelete