让我们考虑下面的程序。
#include<stdio.h>
void swap(char *str1, char *str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}
int main()
{
char *str1 = "cxydh";
char *str2 = "52cxydh";
swap(str1, str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
程序的输出是str1 是 cxydh, str2 是 52cxydh。所以上面的 swap() 函数不会交换字符串。该函数仅更改局部指针变量,并且更改不会反映在函数外部。
让我们看看交换字符串的正确方法:
方法 1(交换指针)
如果您对字符串(而不是数组)使用字符指针,则更改 str1 和 str2 以指向彼此的数据。即,交换指针。在一个函数中,如果我们想改变一个指针(显然我们希望改变反映在函数之外),那么我们需要将一个指针传递给该指针。
#include<stdio.h>
/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
int main()
{
char *str1 = "cxydh";
char *str2 = "52cxydh";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
如果使用字符数组存储字符串,则无法应用此方法。方法2(交换数据)
如果您使用字符数组来存储字符串,那么首选的方法是交换两个数组的数据。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* Swaps strings by swapping data*/
void swap2(char *str1, char *str2)
{
char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
free(temp);
}
int main()
{
char str1[10] = "cxydh";
char str2[10] = "52cxydh";
swap2(str1, str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
此方法不适用于存储在只读内存块中的字符串。