Intermediate Business Programming with C++

Null Pointers & Pointers to void

Null Pointers

Global pointers are initialized automatically to zero. However, local pointers are not. Therefore local pointers must be explicitly initialized. One way to do this is by using the NULL pointer (i.e. a pointer to the value NULL i.e. 0). This is done in the following manner:

stuffType *ptrStuff = NULL;

NULL is stored in the header file iostream. Effectively, NULL is the integer 0. This is the only integer that may be used as the value of a pointer. For example the following should cause a compiler error:

stuffType *ptrStuff = 50;

While the above would create a compiling error, using typecasting on the integer as in the following will compile:

stuffType *ptrStuff = (stuffType*) 50;

The same would be true for values other than 50.

Null pointers can then be used to test conditionals as in the following:

if (!ptrStuff)

For example see NULLPTR.CPP.

One of the reasons to set a pointer to the value: NULL is that you may use a pointer before it has been assigned the address of an appropriate variable. When in this state, you may try to use it and thereby cause a bug which will be very hard to find.

Pointers to Void

There are also times in which it is desirable to define a pointer without specifying the type of data to which it points. This is possible by defining it to be a pointer to void. For example:

void *ptrStuff;

While a void pointer can contain the address of any variable, it can not be used to dereference the contents of the variable. In addition the address contained in a void pointer may be transferred to a pointer of the correct type but type casting must be used. However if the void pointer is dereferenced into an incorrect data type the outcome is unpredictable. See VOIDPTR.CPP

Категории