Q70 What is the difference between const char *ptr, char * const ptr, and const char * const ptr?

const char *ptr – This is a pointer to a constant char. One cannot change the value pointed at by ptr, but can change the pointer p itself see an example given below:

*ptr = ‘A’;  /* illegal operation */

ptr = “Gyantoday”;  /* legal operation */

Note that even char const *p is the same!

 

char * const ptr – Here pointer is a constant. The data can be changed but we cannot assigned new address to the pointer. Example given below:

char * const ptr = “Gyantoday”;

*ptr = “Pointer”;  /* Legal operation */

++ptr;  /* Illegal operation- error: increment of read-only variable ‘ptr’ */

 

const char const *ptr – Here pointer and value pointed by pointer both are constant. See an example below:

const char const *ptr = “Gyantoday”;

*ptr = “Pointer”  /* illegal operation */

++ptr;  /* illegal operation */

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.