2

I don't understand so well how this code works:

#include <stdio.h>
void gswap(void* ptra, void* ptrb, int size)
{
 char temp;
 char *pa = (char*)ptra;
 char *pb = (char*)ptrb;
 for (int i = 0 ; i < size ; i++) {
   temp = pa[i];
   pa[i] = pb[i];
   pb[i] = temp;
 }
}

int main()
{
    int a=1, b=5;
    gswap(&a, &b, sizeof(int));
    printf("%d , %d", a, b)
}

What I understand is that char has 1 byte(size) in memory and we are using pointers to swap each byte of the int value(4 bytes).
But in the end, how it is possible to dereference a char pointer to int value?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
sam0101
  • 373
  • 1
  • 4
  • 15
  • 1
    `gswap` is not dereferencing the `int` value, it's just swapping the bit patterns of the `int` byte by byte. The cast to `char*` is a trick used to get the an individual byte of the object. – Pablo Mar 04 '18 at 23:49
  • @Pablo Wouldn't using `stdint.h` and casting to `uint8_t*` be more readable, maybe? – Bernardo Meurer Mar 05 '18 at 00:05
  • @BernardoMeurer `uint8_t` would add clarity as so would `unsigned char`. Yet not really needed. Note `uint8_t` is an optional type although quite common. – chux - Reinstate Monica Mar 05 '18 at 00:27
  • @chux Yeah, I meant it mostly for clarity, I never liked using char to represent bytes :P – Bernardo Meurer Mar 05 '18 at 00:34

1 Answers1

4

Let's try and figure this out, step by step, with code comments

#include <stdio.h>

//gswap() takes two pointers, prta and ptrb, and the size of the data they point to
void gswap(void* ptra, void* ptrb, int size)
{
    // temp will be our temporary variable for exchanging the values
    char temp;
    // We reinterpret the pointers as char* (byte) pointers
    char *pa = (char*)ptra;
    char *pb = (char*)ptrb;
    // We loop over each byte of the type/structure ptra/b point too, i.e. we loop over size
    for (int i = 0 ; i < size ; i++) {
        temp = pa[i]; //store a in temp
        pa[i] = pb[i]; // replace a with b
        pb[i] = temp; // replace b with temp = old(a)
    }
}

int main()
{
    // Two integers
    int a=1, b=5;
    // Swap them
    gswap(&a, &b, sizeof(int));
    // See they've been swapped!
    printf("%d , %d", a, b);
}

So, basically, it works by going over any given datatype, reinterpreting as bytes, and swapping the bytes.

Bernardo Meurer
  • 2,295
  • 5
  • 31
  • 52