[Solved] Cast pointer to reference pointer


This will do what you think you want, but it’s totally NOT recommended. Templates (or std::swap) really are the right answer here.

First, define an inline function to take void **

inline void SWAP_POINTERS2(void** p1,void** p2)
{
    void* temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

Then, define a macro to perform unpleasant casts.

#define SWAP_POINTERS(a,b) SWAP_POINTERS2((void **) &a, (void **) &b)

Or, if you prefer using static_cast:

  #define SWAP_POINTERS(a,b) SWAP_POINTERS2(static_cast<void**>(static_cast<void *> (&a)), static_cast<void**>(static_cast<void *>(&b)))

Now this “works” to the extent that it compiles and does what you want. I have no idea how you’d then use the swapped pointers, of course…

unsigned int* a;
double* b;

SWAP_POINTERS(a,b);

7

solved Cast pointer to reference pointer