Generic Pointers and Casts
Recall that pointer variables in C have types just like other variables. The main reason for this is so that when we dereference a pointer, the compiler knows the type of data being pointed to and can access the data accordingly. However, sometimes we are not concerned about the type of data a pointer references. In these cases we use generic pointers, which bypass C’s type system.
Generic Pointers
Normally C allows assignments only between pointers of
the same type. For example, given a character pointer
sptr
(a string) and an integer pointer
iptr
, we are not permitted to assign
sptr
to iptr
or iptr
to
sptr
. However, generic pointers can be
set to pointers of any type, and vice versa. Thus, given a generic
pointer gptr
, we are permitted to assign
sptr
to gptr
or gptr
to
sptr
. To make a pointer generic in C, we
declare it as a void pointer .
There are many situations in which void pointers are useful. For example, consider the standard C library function memcpy, which copies a block of data from one location in memory to another. Because memcpy may be used to copy data of any type, it makes sense that its pointer parameters are void pointers. Void pointers can be used to make other types of functions more generic as well. For example, we might have implemented the swap2 function presented earlier so that it swapped data of any type, as shown in the following code:
#include <stdlib.h> #include <string.h> int swap2(void *x, void *y, int size) { void *tmp; if ...
Get Mastering Algorithms with C now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.