C - Pointer Constant Pointers

Introduction

To ensure that the address stored in a pointer cannot be changed, use the const keyword in the declaration of the pointer.

The following code ensures that a pointer always points to the same thing:

int count = 43;
int *const pcount = &count;       // Defines a constant pointer

The second statement declares and initializes pcount and indicates that the address stored must not be changed.

So the following statements will result in an error message when you compile:

int item = 34;
pcount = &item;                   // Error - attempt to change a constant pointer

You can still change the value that pcount points to using pcount:

*pcount = 345;                    // OK - changes the value of count

This references the value stored in count through the pointer and changes its value to 345.

You could use count directly to change the value.

You can create a constant pointer that points to a value that is also constant:

int item = 25;
const int *const pitem = &item;

The pitem is a constant pointer to a constant so everything is fixed.

You can still change the value of item directly though.

To make everything fixed and inviolable, specify item as const.