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
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.