Learn C - C Pointer Value

Testing for a NULL Pointer

Suppose that you create a pointer like this:

int *pvalue = NULL;

NULL is a special symbol in C that represents the pointer.

The symbol is often defined as ((void*)0).

When you assign 0 to a pointer, it's the equivalent of setting it to NULL, so you could write the following:

int *pvalue = 0;

Because NULL is the equivalent of zero, if you want to test whether pvalue is NULL, you can write this:

   // the pointer is NULL! . . .

When pvalue is NULL, !pvalue will be true.

Alternatively, you can write the test as follows:

if(pvalue == NULL)
  //the pointer is NULL! . . .

Pointers to Constants

You can use the const keyword on pointer to indicate that the value pointed to must not be changed.

Here's an example of a declaration of a pointer to a const value:

long value = 9L;
const long *pvalue = &value;               // Defines a pointer to a constant

You have only asserted that what pvalue points to must not be changed.

You are quite free to do what you want with value:

value = 7L;

The value pointed to has changed, but you did not use the pointer to make the change.

Of course, the pointer itself is not constant, so you can still change what it points to:

long number = 8L;
pvalue = &number;                 // OK - changing the address in pvalue

Constant Pointers

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

Here's how you could ensure 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 though:

*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 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 cannot change the address stored in pitem and you cannot use pitem to modify what it points to.

You can still change the value of item directly though.

If you wanted to make everything fixed and inviolable, you could specify item as const.

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