【问题标题】:What does the -> operator do in C? [duplicate]-> 运算符在 C 中的作用是什么? [复制]
【发布时间】:2017-04-24 15:16:49
【问题描述】:

我必须在明天上午 10 点之前学习这个,因为我是个拖延者。

我知道如果你喜欢都可以骂我。我在这里所拥有的是,我必须理解指针才能理解链表,而在使用指针时让我感到困惑的一件事是使用 -> 时。

根据我的谷歌搜索,它改变了变量指向的内容?

当教授给我的示例代码中有行时,这让我感到困惑,例如此代码中的 temp = temp->head 或当它声明 printf("%d", temp->num);

谁能帮忙解释一下?先感谢您。

    #include <malloc.h>
    #include <stdio.h>
    #include <stdlib.h>

    struct node
    {
        int num;
        struct node *ptr;
    };

     typedef struct node NODE;

     int main()
     {
      NODE *head, *temp = 0, *first;
    int count = 0;
    int choice = 1;

    while(choice)
    {
        head = (NODE *)malloc(sizeof(NODE));

    printf("Enter the value: \n");
    scanf("%d", &head->num);

    if (first != 0)
    {
        temp->ptr = head;
        temp = head;
    }
    else
        first = temp = head;
    fflush(stdin);
    printf("Do you want to continue?");
    scanf("%d", &choice);
    }

    temp->ptr = 0;
    temp = first;
    printf("\nStatus of the linked list");

    while (temp != 0)
    {
        printf("%d->" temp->num);
    count++;
    temp = temp->ptr;
    }
    printf("NULL\n");
    printf("Number of entries in linked list %d", count);
    return 0;
    }
}

【问题讨论】:

    标签: c pointers linked-list


    【解决方案1】:

    它解引用一个指向结构的指针,并访问该结构的成员。

    以您的代码为例:

    temp->ptr = head;
    

    这是一样的

    (*temp).ptr = head;
    

    “箭头”运算符使它更简单一些。

    如果你好奇的话,有some history behind the -&gt; operator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2011-04-18
      • 2021-03-28
      • 2014-01-15
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多