Tuesday, May 18, 2010

Constant Pointers and Pointers to Constants

Consider the following declaration:



char A_char = 'A';
char * myPtr = &A_char;
This is a simple declaration of the variable myPtr. myPtr is a pointer to a character variable and in this case points to the character 'A'.
Don't be confused about the fact that a character pointer is being used to point to a single character—this is perfectly legal! Not every character pointer has to point to a string.
Now consider the following three declarations assuming that char_A has been defined as a type char variable.:
const char * myPtr = &char_A;
char * const myPtr = &char_A;
const char * const myPtr = &char_A;
What is the difference between each of the valid ones? Do you know?
They are all three valid and correct declarations. Each assigns the addres of char_A to a character pointer. The difference is in what is constant.
The first declaration:
const char * myPtr
declares a pointer to a constant character. You cannot use this pointer to change the value being pointed to:
char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J';    // error - can't change value of *myPtr
The second declaration,
char * const myPtr
declares a constant pointer to a character. The location stored in the pointer cannot change. You cannot change where this pointer points:
char char_A = 'A';
char char_B = 'B';

char * const myPtr = &char_A;
myPtr = &char_B;    // error - can't change address of myPtr
The third declares a pointer to a character where both the pointer value and the value being pointed at will not change.
Pretty simple, but as with many things related to pointers, a number of people seem to have trouble.

1 comment:

  1. There is some mnemonic to identify this . but forget , will add to this blog once come to mind..

    ReplyDelete