Search code examples
cpointersintegerswapdereference

Using integer declaration instead of pointer integer when pointer swaping in C language


I have seen many articles discussing pointer swapping, in many of them, they use this code:

void ptr_swap(int **p1, int **p2)
{
     int *temp = *p1;
     *p1 = *p2;
     *p2 = temp;      
}

but I am not clear as to why it is necessary to declare temp as a pointer rather than as a natural integer. When I tested it, it did not make any difference.

void ptr_swap(int **p1, int **p2)
{
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

Thanks!


Solution

  • Because the type of *p1 is int*. This type is not compatible with int and a cast would be required. Moreover, the cast itself is implementation defined and int may not be long enough to store a value of a pointer without loosing bits.

    It will likely fail on 64-bit machine where pointers are 64-bit-long and int is 32-bit-long.

    Btw consider using the macro below to implement swap operation that works with any type and provides type checking:

    #define SWAP(a,b)                      \
      do {                                 \
        char tmp__[sizeof(a)];             \
        void *va__ = &(a);                 \
        void *vb__ = &(b);                 \
        (void)sizeof(&(a) - &(b));         \
        memcpy(tmp__, va__, sizeof tmp__); \
        memcpy( va__, vb__, sizeof tmp__); \
        memcpy(vb__, tmp__, sizeof tmp__); \
      } while (0)