Monday, May 24, 2010

void Pointers

A pointer to void, or void pointer for short, is a pointer with the type void *. As there are no objects with the type void, the type void * is used as the all-purpose pointer type. In other words, a void pointer can represent the address of any object but not its type. To access an object in memory, you must always convert a void pointer into an appropriate object pointer.

To declare a function that can be called with different types of pointer arguments, you can declare the appropriate parameters as pointers to void. When you call such a function, the compiler implicitly converts an object pointer argument into a void pointer. A common example is the standard function memset( ), which is declared in the header file string.h with the following prototype:

void *memset( void *s, int c, size_t n );

The function memset( ) assigns the value of c to each of the n bytes of memory in the block beginning at the address s. For example, the following function call assigns the value 0 to each byte in the structure variable record:

struct Data { /* ... */ } record;
memset( &record, 0, sizeof(record) ); 

The argument &record has the type struct Data *. In the function call, the argument is converted to the parameter's type, void *.

The compiler likewise converts void pointers into object pointers where necessary. For example, in the following statement, the malloc( ) function returns a void pointer whose value is the address of the allocated memory block. The assignment operation converts the void pointer into a pointer to int:

int *iPtr = malloc( 1000 * sizeof(int) ); 

Source: C in a Nutshell - O'Reilly Media

No comments:

Post a Comment