c - 在C中通过引用递归传递字符串

标签 c string recursion pass-by-reference

期望的输出是:

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/

相关文章:

r - 如何翻译字符串中的所有字符

sql - 递归 SQL 查询加速非索引查询

c - 哪个 API 用于在 Windows 上加密休眠文件?

java - 为什么 String.chars() 在 Java 8 中是整数流?

c - 从控制台读取值会覆盖结构

list - 在 Haskell 中编写列表上的递归函数

c++ - 递归求平方根和

c++ - 我如何将接受的套接字作为参数发送到函数

c - 使用指针到指针的方法读取和打印矩阵

c - DevC++ 中的 Allegro 错误