【问题标题】:Generic swap function using pointer to char in C在 C 中使用指向 char 的指针的通用交换函数
【发布时间】:2018-03-04 23:35:13
【问题描述】:

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

#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 指针呢?

【问题讨论】:

  • gswap 没有取消引用int 值,它只是逐字节交换int 的位模式。转换为 char* 是一种用于获取对象的单个字节的技巧。
  • @Pablo 不会使用stdint.h 并转换为uint8_t* 更具可读性,也许吧?
  • @BernardoMeurer uint8_t 会增加清晰度,unsigned char 也会如此。然而并不是真的需要。注意uint8_t 是一个可选类型,虽然很常见。
  • @chux 是的,我的意思主要是为了清楚起见,我从不喜欢使用 char 来表示字节:P

标签: c pointers char void-pointers char-pointer


【解决方案1】:

让我们试着用代码 cmets 一步一步解决这个问题

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

因此,基本上,它通过遍历任何给定的数据类型、重新解释为字节并交换字节来工作。

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 2021-01-26
    • 2011-04-24
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多