[英]Why does my function not modify the value of variable in a struct in 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)
傳遞的值tmp
到foo
,然后foo
修改了在指向事物。 它將tmp[2]
更改為指向"44"
。 tmp[2]
是tmp
指向的東西之一; 不是tmp
。
類似地,在bar(str)
, str
是一個指針,並且var
不會更改指針的值。 而是, bar
更改str
指向的字符串中的字符之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.