1.C 代码,用于交换存储在字符数组中的两个字符串。
#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[10] = "geeks";
char str2[10] = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
2.交换只读存储器中存储的两个字符串的C代码。
#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 = "geeks";
char *str2 = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
这两个是交换两个字符串的代码(一个字符串存储在堆栈中,另一个存储在只读内存中)。 他们会一样工作吗? 据说第一个代码将无法正常工作。 如果是,为什么?
最佳答案
第一个示例将不起作用,因为在调用 swap1
函数时您并没有真正将指针传递给指针,而是将指针传递给数组。
表达式&str1
的类型不是char**
,而是char (*)[10]
。这是一个非常大的差异,在尝试取消引用这些指针并交换它们时会导致各种问题。
关于c - 交换存储在字符数组 C 中的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39449583/