簡體   English   中英

圓括號內的指針

[英]pointer inside round brackets

void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
            (struct node*) malloc(sizeof(struct node));

    /* put in the data  */
    new_node->data  = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);   

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

如果我沒記錯的話,在指針上放一個括號意味着調用一個函數? 如果這是真的我真的不明白為什么* head_ref上有括號。 我喜歡一個小解釋,為什么我需要在此代碼中的*head_ref上使用括號。

在這種特殊情況下,括號除了澄清程序員的意圖之外沒有其他目的,即他們想要取消引用head_ref

請注意, head_ref是指向指針的指針,因此在這種情況下, new_node->next被設置為指向鏈表的原始頭部,然后head_ref指向的指針被更新為指向new_node ,這是現在是列表的開頭。

正如Michael Krelin在下面指出的那樣,在指針周圍放置括號並不意味着它是一個調用函數或指向函數的指針。 如果你看到這個: (*head_ref)() 那么它將調用head_ref指向的函數。

調用函數看起來像這樣:

(*some_func_pointer)();

你的案例中的括號是沒有意義的。

此外,無需在C中轉換mallocvoid* )的結果。

它只是在你的情況下取消引用指針。

你說的那個: “在指針上放一個括號意味着調用一個函數”

如果*之后是函數指針,則為真。 基本上它取決於指針的類型。

這些括號僅用於分組。

通過指向它的指針調用函數:

(* funcPointer)(param1,param2)
^             ^^         ^
|             |`---------`--- These brackets tell the compiler 
|             |               it's a function call
|             |
`-------------`---------------These brackets just group the * 
                              with the variable name

對於不帶參數的函數,它只是()

您的示例在變量后面沒有一對括號,因此它不是函數調用。

暫無
暫無

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

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