期望的输出是:
orange 1
apple 2
apple 3
相反,我得到了这个:
orange 1
apple 2
orange 3
当我执行我的代码时:
#include <stdio.h>
#include <stdlib.h>
void change(char *word) { // passing pointer to subroutine
if (word != "apple") { // WARNING FROM COMPILER
printf("%s 1\n", word); // value state #1
word = "apple"; // change "orange" to "apple"
change(word); // recursion happens here
} else
printf("%s 2\n", word); // value state #2
}
int main() {
char word[] = "orange";
change(word); // pass string by reference
printf("%s 3\n", word); // value state #3
return 0;
}
我正在使用的 gcc 编译器
给我以下警告:
comparison with string literal results in unspecified behavior [-Waddress] at line 5:
if (word != "apple") { // WARNING FROM COMPILER
我已经尝试了很多方法,但仍然未能按照 #3 state print 中所示进行从 main()
到 change()
的正确传递引用.它也应该递归工作。
你能发现我的代码有什么问题吗?
最佳答案
您不能使用相等或不等运算符比较字符串,它会比较指针 word
和数组"apple"
衰减到。
此外,您不能在代码中使用赋值运算符,因为它只会在函数内部赋值给局部指针变量 word
。
要解决第一个问题,请使用 strcmp
相反,第二次使用strcpy
.但是在使用 strcpy
时要小心,不要复制超出原始数组末尾的长字符串。
关于c - 在C中通过引用递归传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618919/