簡體   English   中英

在C中通過引用遞歸傳遞字符串

[英]Pass string by reference recursively in C

所需的輸出是:

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 compiler給我以下警告:

與字符串文字的比較導致第 5 行的未指定行為 [-Waddress]

if (word != "apple") {         // WARNING FROM COMPILER

我已經嘗試了很多方法,但仍然未能按照 #3 狀態打印中所示進行從main()change()的正確傳遞引用。 它也應該遞歸工作。

你能發現我的代碼有什么問題嗎?

您不能使用相等或不等運算符比較字符串,它會比較指針word和數組"apple"衰減到的字。

此外,您不能在代碼中使用賦值運算符,因為它只會在函數內部賦值給局部指針變量word

要解決第一個問題,請改用strcmp ,第二個問題請使用strcpy 但是在使用strcpy時要小心,這樣你就不會復制一個超出原始數組末尾的長字符串。

!=引用不起作用。 您需要使用strcmp()進行比較。

同樣,更改緩沖區的內容需要strcpy()

此外,緩沖區的大小不正確,因為“apple”創建了一個 6 個字符的緩沖區(包括結尾的 '\0' NULL 字符)。 “orange”需要一個大小為 7 的緩沖區,因此如果初始單詞小於 orange(盡管您的示例代碼確實將其設置為橙色),您也會遇到緩沖區溢出問題。

你應該讓你的緩沖區足夠大以適應你的單詞所需的最大大小,並調用strlen()來檢查新單詞的大小與已知的最大緩沖區大小,假設你想要一個更一般的情況而不僅僅是“蘋果”和您的更改功能中的“橙色”。

正確解決這些問題后,您應該會看到更好的結果。

試試這些改變:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void change(char *word){         //passing pointer to subroutine
    if(!strcmp(word,"apple")){         //returns 0 when strings are equal
        printf("%s 1\n", word);  //value state #1
        strcpy(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;
}

strcmp() 說明在這里

第一:請尊重警告。 不要比較字符串文字。

但是,談到為什么沒有得到預期結果的原因是,雖然你傳遞的是指針,但你是按值傳遞它。 因此,即使您認為您正在為變量 word 分配一個新地址,它也不會反映在您的調用函數中。

解決方案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void change(char *word) {         
    if (strcmp(word, "apple")) {        
        printf("%s 1\n", word);  
        strcpy(word, "apple");          
        change(word);            
    } else
        printf("%s 2\n", word);  // value state #2
}

int main() {
    char word[20]; 

    strcpy(word, "orange");
    change(word);                // pass string by reference
    printf("%s 3\n", word);      // value state #3 

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM