Reputation: 63
Is it possible to swap the content of two void pointers ? I tried swapping the values by dereferencing the two pointers:
void* a = (void*)50;
void* b = (void*)90;
*a = *b;
However, the last line throws an error since it's impossible to dereference a void pointer.
I think it can be achieved by first casting the value of b to an int and then cast it back to a void* like this:
void* a = (void*)50;
void* b = (void*)90;
int value = (int)b;
a = (void*)value; //a now equals b
Unfortunately, that requires us to know what type a and b are "supposed" to be (I don't know if such a description is correct), in that case, they were ints. Is it possible to swap the content of two void pointers without knowing their "original" types ?
Thanks.
Upvotes: 0
Views: 349
Reputation: 238371
Is it possible to swap the content of two void pointers without knowing their "original" types?
If you have no knowledge of the types then no, it is not possible. At the very least, you must know the size of the type. And that is sufficient only for trivially copyable types.
Upvotes: 4
Reputation: 119239
No, that's not possible. In order to do such a thing, the information about the sizes of the objects pointed to by the two pointers would have to be present at runtime somewhere, which isn't the case. Furthermore, there are types that are not trivially copyable, and as such, swapping their bytes might not swap their values, and could cause undefined behaviour.
Upvotes: 7