代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int swap1(char **p1, char **p2) {
char * temp = NULL;
temp = *p1;
*p1 = *p2;
*p2 = temp;
return 0;
}
int swap2(char **p1, char **p2) {
char temp[1024];
strcpy(temp, *p1);
strcpy(*p1, *p2);
strcpy(*p2, temp);
return 0;
}
int main(void * arg) {
char str1[] = "hello world";
char * p1 = str1;
char str2[] = "HELLO WORLD";
char * p2 = str2;
printf("\n");
printf("before swap: p1 = %s, p2 = %s\n",p1, p2);
printf("before swap: str1 = %s, str2 = %s\n",str1, str2);
printf("\n");
swap1(&p1, &p2);
printf("after swap1: p1 = %s, p2 = %s\n",p1, p2);
printf("after swap1: str1 = %s, str2 = %s\n",str1, str2);
printf("\n");
swap2(&p1, &p2);
printf("after swap2: p1 = %s, p2 = %s\n",p1, p2);
printf("after swap2: str1 = %s, str2 = %s\n",str1, str2);
printf("\n");
}
结果:
swap1只是交换了两个指针的地址
swap2才交换了两个字符串的值