在 C 中使用指向 char 的指针的通用交换函数

Generic swap function using pointer to char in C

我不太明白这段代码是如何工作的:

#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)
}

据我了解,char 在内存中有 1 个字节(大小),我们正在使用指针交换 int 值(4 个字节)的每个字节。
但最后,如何取消引用指向 int 值的 char 指针?

让我们尝试通过代码注释逐步解决这个问题

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

所以,基本上,它的工作原理是遍历任何给定的数据类型,重新解释为字节,然后交换字节。