因为字符指针作为函数参数,交换的只是形参的值,其结果不能传回main函数,如果需要改变字符指针指向的地址,需要把字符指针的地址传入函数swap,然后再在函数中解引用让字符指针指向新的地址,修改如下:
#include <stdio.h>
void swap(char **str1,char **str2){
char * temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main(void){
char * str1 = "Hello";
char * str2 = "World";
swap(&str1,&str2);
printf("str is %s , str2 is %s",str1,str2);
getchar();
return 0;
}
swap函数里,所有变量前面都要加星号
#include <stdio.h>
#include <string.h>
void swap(char *p1,char *p2)
{
char temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
char *a = "Hello";
char *b = "World";
swap(&a,&b);
printf("a=%s,b=%s",a,b);
return 0;
}