Sams Teach Yourself C in 21 Days

(singke) #1

TypevoidPointers ..............................................................................................


You’ve seen the voidkeyword used in a function declaration to specify that the function
either doesn’t take arguments or doesn’t return a value. The voidkeyword can also be
used to create a generic pointer—a pointer that can point to any type of data object. For
example, the statement
void *ptr;
declaresptras a generic pointer. ptrpoints to something; you just haven’t yet specified
what.
The most common use for type voidpointers is in declaring function parameters. You
might want to create a function that can handle different types of arguments. You can
pass it a type intone time, a type floatthe next time, and so on. By declaring that the
function takes a voidpointer as an argument, you don’t restrict it to accepting only a sin-
gle data type. If you declare the function to take a voidpointer as an argument, you can
pass the function a pointer to anything.
Here’s a simple example: You want to write a function that accepts a numeric variable as
an argument and divides it by two, returning the answer in the argument variable. Thus,
if the variable valholds the value 4, after a call to half(val)the variable valis equal to


  1. Because you want to modify the argument, you pass it by reference. Because you want
    to use the function with any of C’s numeric data types, you declare the function to take a
    voidpointer:
    void half(void val);
    Now you can call the function, passing it any pointer as an argument. There’s one more
    thing you need, however. Although you can pass a voidpointer without knowing what
    data type it points to, you can’t dereference the pointer. Before the code in the function
    can do anything with the pointer, it must know the data type. You do this with a typecast,
    which is nothing more than a way of telling the program to treat this voidpointer as a
    pointer to a specific type. If pvalis a voidpointer, you typecast it as follows:
    (type
    )pval
    Here,typeis the appropriate data type. To tell the program that pvalis a pointer to type
    int, write
    (int )pval
    To dereference the pointer—that is, to access the intthatpvalpoints to—write
    (int *)pval


520 Day 18

29 448201x-CH18 8/13/02 11:14 AM Page 520

Free download pdf