c - 使用空指针交换函数

标签 c swap void-pointers

<分区>

我想制作一个可以普遍用于任何数据类型的交换函数。我知道以下函数适用于整数:

void swap(void *a, void *b)
{
    int temp;
    temp = *(int*)a;
    *(int*)a = *(int*)b;
    *(int*)b = temp;
}

这适用于字符串:

void swap(void *a, void *b)
{
    void *temp;
    temp = *(void**)a;
    *(void**)a = *(void**)b;
    *(void**)b = temp;
}

最佳答案

如果你也传递指针对象的大小(比如在 qsort 中),那么你可以这样做:

void swap(void * a, void * b, size_t len)
{
    unsigned char * p = a, * q = b, tmp;
    for (size_t i = 0; i != len; ++i)
    {
        tmp = p[i];
        p[i] = q[i];
        q[i] = tmp;
    }
}

用法:

struct Qux x, y;
swap(&x, &y, sizeof(Qux));

(您可能希望向指针添加 restrict 限定符,或者以其他方式测试自交换。)

关于c - 使用空指针交换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596151/

相关文章:

c - 为什么我会在这个 while 循环中遇到段错误?

c - 让父进程等待并根据需要多次运行 linux 命令

android - 确定在 Android 中运行的应用程序的物理内存地址

c++ - 为什么交换运营商的提议被否决了?

c++ - iter_swap() 与 swap() - 有什么区别?

c - 具有指向父结构的指针的结构 : best approach

C: 空数组*

c++ - 在 C/C++ 中使用 %f 确定 float 的输出(打印)

c - 通过 void 指针传递的 GDBM 对象丢失/损坏

c - 函数 ‘gmtime_r’ 的隐式声明