Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse an array parameter as void pointer

I have similar "generic" procedure like qsort, which has a void pointer (pointing at an array) and also a function pointer parameter. This function should work on any type of array.

Example:

void do_something(void * array, int count, int size, void (*test)(const void*)){
    int i;
    for(i=0; i<count; i++){
        test(array + (index * size));
    }
}

This however gives me the following warning (gcc test.c -pedantic-errors):

error: pointer of type ‘void *’ used in arithmetic [-Wpedantic]

And after some research I found out it's a bad practice to use void pointers like this. (E.g. Pointer arithmetic for void pointer in C)

So how does the standard library do this kind of stuff for like qsort? Looking at this code: (http://aturing.umcs.maine.edu/~sudarshan.chawathe/200801/capstone/n/qsort.c), I see the following:

void
_quicksort (void *const pbase, size_t total_elems, size_t size,
        __compar_fn_t cmp)
{
  register char *base_ptr = (char *) pbase;
  ....
  char *lo = base_ptr;
  char *hi = &lo[size * (total_elems - 1)];
  ...
}

Are they casting to (char *) regardless of the actual type?

like image 500
Aaron Avatar asked Sep 01 '26 22:09

Aaron


2 Answers

i asked similar question Can I do arithmetic on void * pointers in C?.

Void * arithmetic is not defined. What does it mean to add 1 to a void pointer ? Most compilers (if they allow it) treat it as incrementing by sizeof(char) ("the next byte") but warn you.

So the right thing to do is to explicitly make it do what you want -> cast to char* and increment that

like image 135
pm100 Avatar answered Sep 03 '26 13:09

pm100


Pointer arithmetic on incomplete data type void is not legal and that is what the compiler is complaining.

As you can see in the _quicksort() the pointer is a constant one so that you can't modify the address the pointer is pointing to. There is no arthmetic operation happening on the void pointer.

like image 36
Gopi Avatar answered Sep 03 '26 13:09

Gopi