Search This Blog

Tuesday, March 10, 2015

Difference between constant pointer and pointer to constant in c


Constant pointer :
These type of pointers we can not change the address pointed by the pointers but the values pointed by those pointers can be changed.

<data type> *const  <variable-name>;
ex: int *const ptr;

main()
{
     int i =10 , j = 20;

     int *const ptr = &i;
   
    ptr = &j; // Not allowed
    *ptr = 20; //Allowed
}


Pointer to constant :
These types of pointers are the one in which we can change the address but we can not change the value they are pointed to.

const <data-type> * <variable-name>;
ex: const int *ptr;

main()
{
     int i =10 , j = 20;

     int *const ptr = &i;
   
    ptr = &j; // allowed
    *ptr = 20; //not allowed
}

No comments:

Post a Comment