我有一個從這個討論中提出的問題:C - 修改傳遞給函式的指標的地址
假設我有以下代碼:
#include <stdio.h>
foo(char **ptr){
*ptr ;
}
int main()
{
char *ptr = malloc(64);
char arr[] = "Hello World!";
memcpy(ptr, arr, sizeof(arr));
foo(&ptr);
foo(&ptr);
printf("%s",ptr);
return 0;
}
我想知道這個程式的輸出是什么,我認為它應該是llo World!.
經過一番調查,我發現了上面鏈接的問題,并意識到,在 C 中,函式的引數總是按值傳遞。到目前為止沒有問題。將*ptr ;運算式更改為 ->*ptr = *ptr 1;輸出時變為:llo World!.
在這一點上,我可以說我有點困惑。為了改變指標地址,我們需要一個雙指標。那很好,但是為什么后增量操作不同呢?是因為運算子優先級嗎?
在這里,我在在線 C 編譯器中嘗試了該示例。
uj5u.com熱心網友回復:
后綴遞增運算子的 優先級高于解參考運算子*。所以這:
*ptr ;
決議為:
*(ptr );
所以它改變了引數值本身,而不是它指向的值。你想要:
(*ptr) ;
uj5u.com熱心網友回復:
后綴運算子的優先級高于一元運算子。所以這個表情
*ptr
相當于
*( ptr )
子運算式ptr 的值是指標遞增前的值。
所以實際上你正在增加ptr具有型別的引數char **。所以這種遞增不會改變原來的指標,也沒有意義。
相反,你可以寫
( *ptr )
但是使用一元增量運算子會更清晰,更容易混淆
*ptr
如果你想增加原始指標本身。
uj5u.com熱心網友回復:
正如其他人所解釋的, 比 更重要(具有更高的優先級)*,因此您的函式foo實際上編譯為:
foo (char **ptr) {
ptr = ptr 1; // This modifies the parameter, which is a copy of a variable, copied *specifically* for this function; hence, modifying it will have no effect outside of the function.
*ptr; // This is just an expression; it doesn't actually do anything, as the compiler would tell you if you wrote it this way.
}
如果更改*ptr 為(*ptr) ,該函式將如下作業:
foo (char **ptr) {
*ptr = *ptr 1; // Sets the variable pointed to by ptr to be equal to itself plus one.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360370.html
上一篇:為什么這個指標是8個位元組?
