【问题标题】:pointer inside round brackets圆括号内的指针
【发布时间】:2012-08-21 10:24:14
【问题描述】:
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 上加上括号。

【问题讨论】:

    标签: c pointers brackets


    【解决方案1】:

    在这种特殊情况下,方括号除了阐明程序员的意图之外没有其他用途,即他们想要取消引用 head_ref

    注意head_ref是一个指向指针的指针,所以在这种情况下,new_node->next被设置为指向链表的原始头,然后head_ref指向的指针被更新指向new_node,它现在是列表的开头。

    正如 Michael Krelin 在下面指出的那样,将括号括在指针周围并不意味着它是调用函数或指向函数的指针。如果你看到这个:(*head_ref)()那么这将是对head_ref指向的函数的调用。

    【讨论】:

    • +1 不,指针周围的括号并不意味着调用函数。
    【解决方案2】:

    调用函数看起来像这样:

    (*some_func_pointer)();
    

    你的括号是没有意义的。

    另外,无需将malloc (void*) 的结果转换为 C。

    【讨论】:

      【解决方案3】:

      在您的情况下,它只是在此处取消引用指针。

      你说的那个:“在指针上加括号意味着调用函数”

      如果 * 之后的内容是函数指针,则

      为真。 基本上它取决于指针的类型。

      【讨论】:

        【解决方案4】:

        这些括号仅用于分组。

        通过指针调用函数:

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

        对于不带参数的函数,它只是()

        您的示例在变量后没有一对括号,因此它不是函数调用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-07
          • 1970-01-01
          • 2021-01-11
          • 2010-12-04
          • 2021-10-17
          相关资源
          最近更新 更多