简体   繁体   English

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

[英]Generic swap function using pointer to char in C

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). 我的理解是char在内存中有1个字节(大小),我们正在使用指针交换int值的每个字节(4个字节)。
But in the end, how it is possible to dereference a char pointer to int value? 但是最后,如何将char指针取消引用到int值?

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. 因此,基本上,它可以通过遍历任何给定的数据类型,将其重新解释为字节并交换字节来工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM