c - c 中的链接列表,代码行的解释?

标签 c list pointers linked-list

<分区>

我刚开始学习 c 中的链表。我仍然混淆代码中的第 1 行。 1.什么是temp->data,是指针吗?多变的? 2.什么是temp->next=head,这里的head有NULL值????如果是这样,temp->next 现在变为 NULL ??? 请真的搞砸了这条线,帮帮我。谢谢

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

struct test_struct{
    int data;
    struct test_struct *next;
};

struct test_struct* head=NULL;

int main()
{

    head = NULL;
    struct test_struct* temp = (struct test_struct*)malloc(sizeof(struct test_struct));
    if(NULL==temp)
    {
        printf("error in memory");
        return 0;
    }
    temp->data=5;    // line  1      <----------  what's going on
    temp->next=head; // line 2       <----------  what's going on here?
    head=temp;
    printf("%p\n",head);
    return 0;
}

最佳答案

what is temp->data, is it pointer? variable?

好吧,让我们分解一下:

  1. 什么是温度?它被声明为

    struct test_struct* temp = ...
    

    所以我们知道它是指向 struct test_struct 的指针。

  2. 什么是temp->data?这意味着跟随(取消引用)指针,并获取名为 data 的成员。您的 test_struct 声明为

    struct test_struct {
      int data;
      struct test_struct *next;
    };
    

    因此,我们知道它有一个名为 data 的整数成员。 temp->data 是对该整数的引用。


what is temp->next=head, here head has NULL value???? if so, temp->next become NULL now ???

此代码 NULL 分配给指针temp->next

如果您对这些东西感到困惑,学习在调试器中逐步完成它可能会有所帮助(就像一本好书一样)。

关于c - c 中的链接列表,代码行的解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937113/

相关文章:

flutter - 如何使用 getx 包在 Flutter 中使列表可观察?

C 字符数组导致段错误

c# - List<T> OrderBy 字母顺序

pointers - 如何将对约束字符串的访问传递给 Ada 中的子程序

c - 2维指针存储字符串

c - MPI 发送和接收不适用于超过 8182 双

c# - C++ 库问题

css - 不尊重 GTK3 CSS 颜色 - 即使在官方示例中也是如此

c - C中的多维数组

python - 检查是否可以通过给定长度的跳跃来达到一个数字?