#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void intSwap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void genericSwap (void *a, void *b, size_t size)
{
void *temp = malloc(size);
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
}
int main(int argc, const char * argv[])
{
// swap two integers
int m = 1;
int n = 2;
intSwap(&m, &n);
printf("%d,%d\n", m, n); // 2,1
// generic swap (int test)
int j = 3;
int i = 4;
genericSwap(&j, &i, sizeof(int));
printf("%d,%d\n", j, i); // 4,3
// generic swap (struct test)
typedef struct {
int height;
int weight;
} human;
human tom;
tom.height = 188;
tom.weight = 85;
human jerry;
jerry.height = 190;
jerry.weight = 99;
genericSwap(&tom, &jerry, sizeof(human));
printf("tom: %d, %d jerry: %d, %d\n",
tom.height, tom.weight,
jerry.height, jerry.weight);
//tom: 190, 99 jerry: 188, 85
return 0;
}
本文出自:億恩科技【mszdt.com】
服務(wù)器租用/服務(wù)器托管中國(guó)五強(qiáng)!虛擬主機(jī)域名注冊(cè)頂級(jí)提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|