Question

This might be a very stupid question but i don't understand this:

If i have:

void* a;
void* b;

And I want to implement a generic swap function, why can't I do this:

void swap(void* a, void* b)
{
   void* temp = malloc(sizeof(*a));
   *a = *b;
   *b = *temp;
   free(temp);
}

Thank you

I added this later on:

So i understand now why it is impossible but now i have another question: Since sizeof(*a) is undefined, someone told me i could do this:

#define SWAP(a,b) \
{ \
   void* temp = malloc(sizeof(*a)); \
   memcpy(temp , a , sizeof(*a)); \ 
   memcpy(a, b, sizeof(*a)); \
   memcpy(b, temp, sizeof(*a));
   free(temp);
}

of course i assume a and b are of the same type. Why will this solution work? thank you

Was it helpful?

Solution

You cannot dereference a void *, there is no information about the type of data it's pointing at. So your code won't compile, which is why you cannot do that.

That's the point of void *, it's a "pointer to anything", and there is absolutely no additional information available if you don't add it yourself.

If I have:

char a; /* size 1 */
int b;  /* assume size 4 */

and call:

swap(&a, &b);  /* assuming it compiled */

All information the function gets is the address of the two variables. There's no way for the function (or the compiler) to magically follow those pointers backward and figure out what the sizes of the pointed-to values are. None.

OTHER TIPS

This way you only "copy" the pointer address but not the actual data. once after you freed temp, y becomes an invalid address. Besides that you're not using a or b in any case

To answer your 2nd question, your SWAP() macro will still NOT work as intended if you pass void* pointers to it. Or for that matter, if you pass two pointers of different types. It will work for something like this:

int a = 2, b = 3;
char c = '0', d = '1';
SWAP(&a, &b);
SWAP(&c, &d);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top