问题
It comes when I want to write my own quicksort for educational purpose. This is what I got:
qsort(void* array, int count, int size, int(*compare)(const void*, const void*));
And I have size of each element in array, and pointer to the first element in array. How can I get each individual element in that array?
回答1:
If size was generated with the sizeof operator, it is a multiple of sizeof(char) (which is 1 by definition). So cast the void* into a char*, and move size "characters" at a time.
(((char*)array) + i*size)
回答2:
You would normally do the address arithmetic with char * pointers, e.g. to access element i of array:
char * array_ptr = (char *)array + i * size;
回答3:
Easy enough, cast it to char* and do pointer arithmetic:
char *carray = (char*)array;
char *pointer_to_n = carray + n * size;
BTW, some compilers such as GCC have an extension that allows to do pointer arithmetic to void pointers as if they were pointers to char, but that is non portable.
来源:https://stackoverflow.com/questions/14119680/how-to-get-an-item-from-a-void-pointer-to-array-when-i-know-each-elements-size