自己写一个swap函数交换任意两个相同类型元素的值 对空指针的使用 字节大小的判断(一)
1 #include <stdio.h> 2 struct Point{ 3 int x; 4 double y; 5 Point(int x = 0, double y = 0):x(x), y(y){} 6 void print(){ 7 printf("(%d, %lf)", x, y); 8 } 9 }; 10 void swap (char *a, char *b, size_t width){ 11 char tmp; 12 while(width--){ 13 tmp = *a; 14 *a++ = *b; 15 *b++ = tmp; 16 } 17 } 18 //width是交换两个元素的字节大小,用sizeof 求出 19 void myswap(void *x, void *y, size_t width){ 20 swap((char *)x, (char *)y, width); 21 } 22 int main(){ 23 int inta = 1, intb = 2; 24 printf("before exchange: inta=%d\tintb=%d\n", inta, intb); 25 //交换整形inta和intb的值 26 myswap(&inta, &intb, sizeof(int)); 27 printf("after exchagge: inta=%d\tintb=%d\n", inta, intb); 28 29 char chara = 'a', charb = 'A'; 30 printf("before exchange: chara=%c\tcharb=%c\n", chara, charb); 31 //交换字符chara和字符charb的值 32 myswap(&chara, &charb, sizeof(char)); 33 printf("after exchagge: chara=%c\tcharb=%c\n", chara, charb); 34 35 Point pointa(1, 1.1), pointb(3, 3.3); 36 printf("before exchange: pointa="); pointa.print(); 37 printf("\tpointb="); pointb.print(); printf("\n"); 38 //交换结构体pointa和pointb的值 39 myswap(&pointa, &pointb, sizeof(Point)); 40 printf("before exchange: pointa="); pointa.print(); 41 printf("\tpointb="); pointb.print(); printf("\n"); 42 return 0; 43 }
程序运行结果