# C 语言实现泛型 swap 函数

``````
void  swap(int  *v1, int  *v2)  {

int *temp = v1;

*v1 = *v2;

*v2 = *temp;

}
``````

``````
void  swap(double  *v1, double  *v2)  {

int *temp = v1;

*v1 = *v2;

*v2 = *temp;

}
``````

`泛型swap函数`实现：

``````
void  swap(void  *v1, void  *v2, size_t  size)  {

void *temp = malloc(size);

assert(temp != NULL);

memcpy(temp, v1, size);

memcpy(v1, v2, size);

memcpy(v2, temp, size);

free(temp);

}
``````

• malloc

• memcpy

• free

`swap`函数进行调用，交换两个`int`类型变量的值：

``````
int  main()  {

int a = 123;

int b = 321;

printf("before swap: %d, %d\n", a, b);

swap(&a, &b, sizeof(int));

printf("after swap: %d, %d\n", a, b);

return 0;

}
``````

``````
before swap: 123, 321

after swap: 321, 123
``````

`swap`函数进行调用，交换两个`double`类型变量的值：

``````
int  main()  {

double a = 123;

double b = 321;

printf("before swap: %f, %f\n", a, b);

swap(&a, &b, sizeof(double));

printf("after swap: %f, %f\n", a, b);

return 0;

}
``````

``````
before swap: 123.000000, 321.000000

after swap: 321.000000, 123.000000
``````

``````
#include  <stdio.h>

#include  <stdlib.h>

#include  <string.h>

#include  <assert.h>
``````

(=￣ω￣=)··· 暂无内容！

5

5

53

21