簡體   English   中英

除返回值外,是否必須將變量的地址發送給函數以在C中修改其值?

[英]Except the return value, does a variable's address must be sent to a function to modify its value in C?

我嘗試了解何時通過C中的函數修改變量的值。

我知道在C語言中,有兩種方法可以更改變量的值:

  • 使用函數的返回值
  • 傳遞變量的地址以修改其內容

這是代碼:

// by address

void foo(int *nb)
{
    *nb = 10;
}

int main(void)
{
     int nb = 5;
     foo(&nb);
     printf("%i\n", *nb); // It prints 10
}

// Code to explain

void foo(char **tab)
{
    tab[2] = "44";
}

void bar(char *str)
{
    str[1] = 'a';
}

int main(void)
{
    char **tmp = malloc(sizeof(char *) * 4);
    char *str = strdup("Hello");

    for (int i = 0; i < 3; ++i)
        tmp[i] = malloc(3);

    tmp[0] = "11";
    tmp[1] = "22";
    tmp[2] = "33";
    tmp[3] = NULL;

    foo(tmp);        // It modifies tmp's value
    bar(str);        // It modifies str's value

    for (int i = 0; i < 3; ++i)
        printf("%s\n", tmp[i]);
    printf("%s\n", str);
}

輸出:
11
22
44
你好

預期:
11
22
33
你好

我原本希望將副本發送給該函數,但是最后,string和char **都被修改了。 為什么在這里修改變量?

您對foo(tmp)評論是“它修改了tmp的值”,但這是不正確的。 tmp是一個指針,並且foo不會修改該指針的值。 呼叫foo(tmp)傳遞的值tmpfoo ,然后foo修改了在指向事物。 它將tmp[2]更改為指向"44" tmp[2]tmp指向的東西之一; 不是tmp

類似地,在bar(str)str是一個指針,並且var不會更改指針的值。 而是, bar更改str指向的字符串中的字符之一。

暫無
暫無

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

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