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;
}
这两个代码用于交换两个字符串(一个字符串存储在堆栈中,另一个字符串存储在只读存储器中)。 他们会一样吗? 据说第一个代码不能正常工作。 如果是这样,为什么?
答案 0 :(得分:4)
第一个示例不起作用,因为您没有在调用swap1
函数时将指针传递给指针,而是将指针传递给数组。
表达式&str1
的类型不是char**
,而是char (*)[10]
。这是一个非常大的区别,当试图取消引用那些指针并交换它们时,这将导致所有类型的问题。