2

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

6
  • 5
    What is sizeof *a when a is of type void*? Commented Jan 29, 2014 at 10:11
  • 1
    I don't even see a memcpy here... Commented Jan 29, 2014 at 10:12
  • 2
    and what are x and y?! Commented Jan 29, 2014 at 10:12
  • @pmr She thinks the code she wrote is an alternative to memcpy, and she's asking why she can't use that alternative. Commented Jan 29, 2014 at 10:13
  • @pmr OP try to NOT use memcpy, that's his question (sort of). Commented Jan 29, 2014 at 10:15

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Daniella Glad to help. Feel free to accept the answer if you like it.
if i would like to create void swap (char*, char*); will (*a) = (*b) work ?
@Daniella Sure, but it would only copy a single character, of course.
1

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

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.