Graphics Programs Reference
In-Depth Information
Naturally, it is far easier just to use the correct data type for pointers
in the first place; however, sometimes a generic, typeless pointer is desired.
In C, a void pointer is a typeless pointer, defined by the void keyword.
Experimenting with void pointers quickly reveals a few things about typeless
pointers. First, pointers cannot be dereferenced unless they have a type.
In order to retrieve the value stored in the pointer's memory address, the
compiler must first know what type of data it is. Secondly, void pointers must
also be typecast before doing pointer arithmetic. These are fairly intuitive
limitations, which means that a void pointer's main purpose is to simply hold
a memory address.
The pointer_types3.c program can be modified to use a single void
pointer by typecasting it to the proper type each time it's used. The compiler
knows that a void pointer is typeless, so any type of pointer can be stored in a
void pointer without typecasting. This also means a void pointer must always
be typecast when dereferencing it, however. These differences can be seen in
pointer_types4.c, which uses a void pointer.
pointer_types4.c
#include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
void *void_pointer;
void_pointer = (void *) char_array;
for(i=0; i < 5; i++) { // Iterate through the int array with the int_pointer.
printf("[char pointer] points to %p, which contains the char '%c'\n",
void_pointer, *((char *) void_pointer));
void_pointer = (void *) ((char *) void_pointer + 1);
}
void_pointer = (void *) int_array;
for(i=0; i < 5; i++) { // Iterate through the int array with the int_pointer.
printf("[integer pointer] points to %p, which contains the integer %d\n",
void_pointer, *((int *) void_pointer));
void_pointer = (void *) ((int *) void_pointer + 1);
}
}
The results of compiling and executing pointer_types4.c are as
follows.
Search WWH ::




Custom Search