c - 链表和指针混淆

标签 c pointers

我正在做我的期末项目,我被介绍到链表,我必须使用它。

在试图理解代码的工作原理后,我感到非常沮丧。这个概念对我来说是完全有道理的。我作为示例给出的代码没有。

typedef struct node_s {
    char name[20]; 
    int age; 
    struct node_s *listp; 
} node;

while (!feof(inp)) {
        temp = (node *)malloc(sizeof(node)); // creation of memory
        fscanf(inp, "%s%d", temp->name, &temp->age);
        if (head == NULL)
            head = temp; // setting the head of the list
        else { 
            tail->listp = temp; // else connecting to previous element
        }
        tail = temp; // updating the current element
        tail->listp = NULL; // setting pointer to null.
    }

我对 tail->listp 每次都设置为 NULL 时如何指向第二个元素感到困惑。为了进一步说明我的困惑,在else语句中tail->listp会指向新的元素,这是可以理解的。

但最后我们将 tail->listp 指向 NULL,它忽略了 else 语句。然而代码工作正常,我在这里非常困惑。

最佳答案

你错过了之前的声明,这是

tail = temp; // updating the current element

在循环中,您创建了一个新元素 temp,并将其链接到列表中。如果它是第一个元素,则本质上通过将它设置为头部和尾部来启动列表。如果它不是第一个元素,则将其链接到列表的末尾。

tail->listp = temp;

然后,您设置tail=temp 以将指针更新为列表末尾,并确保列表末尾的元素指向null

tail->listp = NULL;

你也可以这样做

temp->listp = NULL;
tail=temp;

如果我的眼睛没有让我失望的话,这将是等效的。

关于c - 链表和指针混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55769244/

相关文章:

c - char *const *p 和 char ** const p 的区别

c - 如何修改已传递给 C 函数的指针?

c++ - 如何在 c/c++ 中向参数添加选项? ( Visual Studio 平台2019)

c - 这是一个过于复杂的 pthreads 代码吗?

c - 我如何读取整数文件并将其存储在c中的变量中

c++ - 如何删除 C++ 链表中的节点?

c - printf () 的奇怪行为

c - 输入后下降

c - 将结构中的指针设置为 null

c - 如何在 C 中使用 strlen() 查找字符指针的长度?