How to get an item from a void pointer to array when I know each element's size?

≡放荡痞女 提交于 2019-12-07 20:33:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!