C swap实现任意数据类型调换

C swap实现任意数据类型调换

/* swap.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
    从<string.h>中包含memcpy函数
    void *memcpy(void *p1, const void *p2, size_t n)
    从存储区p1中复制n大小的内存到p2中
*/

/* 整数型数据调换 */
void swap(int *x, int *y)
{
    int tmp = *x;
    *x = *y;
    *y = tmp;
}

/* 使用泛型指针void *ptr实现任意数据类型的调换 */
int swap2(void *x, void *y, int size)
{
    void *tmp;

    /* 分配内存失败 */
    if ((tmp = malloc(size)) == NULL) {
        return -1;
    }
    
    /* 调用memcpy调换数据 */
    memcpy(tmp, x, size);
    memcpy(x, y, size);
    memcpy(y, tmp, size);
    free(tmp);

    return 0;
}

int main(void)
{
    int x = 3, y = 5;
    char l1[5] = "John";
    char l2[5] = "Paul";
    float f1 = 3.14, f2 = 1.782;
    char a = 'a', b = 'b';

    printf("(%d, %d)\n", x, y);
    swap(&x, &y);
    printf("(%d, %d)\n", x, y);
    
    printf("(%s, %s)\n", l1, l2);
    swap2(l1, l2, 5);
    printf("(%s, %s)\n", l1, l2);

    printf("(%f, %f)\n", f1, f2);
    swap2(&f1, &f2, sizeof(float));
    printf("(%f, %f)\n", f1, f2);

    printf("(%c, %c)\n", a, b);
    swap2(&a, &b, sizeof(char));    
    printf("(%c, %c)\n", a, b);

    return 0;
}
posted @ 2019-12-26 14:24  no樂on  阅读(313)  评论(0编辑  收藏  举报