Null Pointers Pointers to void


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:

image from book

 stuffType *ptrStuff = NULL; 

image from book

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:

image from book

 stuffType *ptrStuff = 50; 

image from book

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

image from book

 stuffType *ptrStuff = (stuffType*) 50; 

image from book

The same would be true for values other than 50.

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

image from book

 if (!ptrStuff) 

image from book

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:

image from book

 void *ptrStuff; 

image from book

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




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net