Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

void* considered harmful

Name: Anonymous 2012-12-22 14:24


#include "stdio.h"

void *lsearch(void *addr, void *key, int arraysize, int typesize) {
        for (int i = 0; i < arraysize; i++) {
                if (addr[typesize * i] == *key) return &addr[typesize * i];
        }
        return NULL;
}
 
int main() {
        int is[] = {1,2,3,4,5};
        int i = 5;
        void *address = lsearch(is, &i, 5, sizeof(int));
        printf("%p", address);
        return 0;
}



why do I get these errors?:


generics.c: In function ‘lsearch’:
generics.c:5:11: warning: dereferencing ‘void *’ pointer [enabled by default]
generics.c:5:29: warning: dereferencing ‘void *’ pointer [enabled by default]
generics.c:5:3: error: void value not ignored as it ought to be
generics.c:5:3: error: void value not ignored as it ought to be
generics.c:5:47: warning: dereferencing ‘void *’ pointer [enabled by default]

Name: Anonymous 2012-12-22 17:30

You can't write &addr[typesize * i] because indexing arrays accounts for the number of bytes each value in the array contains. That is to say, &array[2] is equal to array + 8 when array contains 4-byte values (like long ints.)

To do this with void pointers of some known type size, you have to resort to pointer arithmetic and write addr + typesize * i.

You can't dereference two void pointers and compare them like this, because C can't know how much bytes to compare without knowing how big the type is. You can, however, compare memory blocks of some known size using memcmp.

This code gives no warnings on my end:

#include "stdio.h"

void *lsearch(void *addr, void *key, int arraysize, int typesize) {
    int i;
    for (i = 0; i < arraysize; i++) {
        if (memcmp(addr + typesize * i, key, typesize) == 0)
            return addr + typesize * i;
    }
    return NULL;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List