简体   繁体   中英

static_cast and passing void pointers c++

void function(void * array, size_t itemsInArray, size_t sizeOfEachItem, int(*compare)(const void*, const void*))

char * array_ptr = static_cast<char*>(array);

char * ptr1 = items_ptr;
char * ptr2 = items_ptr + 1; 

void * array_ptr_void1 = static_cast<void*>(ptr1);
void * array_ptr_void2 = static_cast<void*>(ptr2);

compare(array_ptr_void1, array_ptr_void2);

So the code I have here is basically what I am trying to accomplish, but I am obviously not understanding the void pointers and passing them to the compare function. What I am basically wanting to do is take the void pointer to array cast it to a char pointer so I can increment through it. Then I want to pass a specific parts to the compare function. I just really need someone to explain to me the logic behind what I am trying to do because I don't seem to understand passing void pointers to the compare function. I can't change the function prototype. My question isn't about incrementing through the char pointer, I understand that part and I am just using item_ptr and item_ptr+1 to demonstrate passing a specific part of the array. The last line of code breaks when I send to parts to be compared, so I need to understand the flaw in my logic. Thanks!

As I understand from your question. There are multiple versions of compare functions with different function names but with void pointers as arguments. These functions are to handle different kinds of data.

And your function is to use these compare functions to compare arrays. I think your function is not complete.

if items_ptr is type of char* you should be using

   char * ptr1 = items_ptr;
   char * ptr2 = items_ptr + sizeOfEachItem; 

If I am not wrong, you are looping/traversing through the buffer(array) pointed by array_ptr using items_ptr.

If so don't use + 1 to go to next item, instead using + sizeOfEachItem. If you want to get nth element use array_ptr + n*sizeOfEachItem

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM