| Why can't you assign values to dereferenced void pointers?

Previous | Memory, C Variables, and Pointers | Next

Q: | Why doesn't this work?
    void *screen_ptr = LCD_MEM;
    *screen_ptr = 0xFF;
When I do this, I get the error "Invalid use of void expression" at the second line. Can't you assign a value to a dereferenced void pointer? If not, what good is a void pointer?
A: | You can not dereference a void pointer, without an explicite typecasting, because the compiler can't know the size of an object pointed to by it. You can do an explicite typecast:
    *(char*)screen = 0xFF;
Or better, if you need to dereference it often, then declare
    unsigned char *screen = LCD_MEM;
i.e. avoid void pointers for this purpose (continue reading to see why such assignment is legal, i.e. assigning LCD_MEM which is a void pointer to a char pointer). Void pointers are used mainly as arguments of functions which represents memory addresses, no matter what is the object located at that addresses. Then, any pointer type (including arrays, which are in fact pointers to the first element of the array) may be passed to such function without warnings and without needness for explicite typecasting. For example, memcpy is such function, and it is declared as:
    void *memcpy (void *source, void *destination, unsigned long len);
Ignore returned type for a moment. So, you can do
    memcpy (LCD_MEM, buffer, 3840);
but you also can do
    memcpy (a, b, 10 * sizeof(long));
assuming that you have declared
    long a[10], b[10];
somewhere in the program. Second, void pointers may be assigned to any other pointer type and vice versa without and warnings and without needness for explicite typecasting. They are usually returned as the result of functions which don't make any assumptions what will be purpose of returned pointer. For example, malloc is such function. It is declared as
    void *malloc (unsigned long len);
So, assuming that you have declared
    char *a;
    int *b;
    long *c;
you can do
    a = malloc (100);
    b = malloc (30 * sizeof(int));
    c = malloc (50 * sizeof(long));
without any problems.