c - LinkedList 打印相同的值

标签 c linked-list

<分区>

我目前正在学习 C,我面临一个链表的情况,我真的不明白。

我创建了以下程序:

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

struct list
{
    int age;
    char name[256];
    struct list *next;
};

void displayList ( struct list *node );

int main( void )
{
    struct list *node = malloc ( sizeof ( struct list ) );

    node->age = 10;
    strcpy( node->name, "Kiara" );

    node->next = malloc ( sizeof ( struct list ) );
    node->next->next = NULL;

    displayList( node );

    free( node->next );
    free( node );
}

void displayList ( struct list *node )
{
    int i = 0;
    struct list *current = node;
    while ( current != NULL )
    {
        printf( "%d) - Age = %d\n%d) - Name = %s\n",i , node->age, i, node->name );
        i++;
        current = current->next;
    }
}

displayList() 调用时,我期望得到这样的结果:

0) - Age = 10
0) - Name = Kiara

1) - Age = GARBAGE
1) - Name = GARBAGE

但我却得到了:

0) - Age = 10
0) - Name = Kiara

1) - Age = 10
1) - Name = Kiara

我在这里做什么/理解错了什么?

最佳答案

您正在循环中打印节点值,但应该打印当前值。节点指针不变。

node->age, node->name

应该是:

current->age, current->name

关于c - LinkedList 打印相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279289/

相关文章:

c - 如何使用 "Modern Compiler Implementation in C"书中的$TIGER?

java - 包含函数链表

请求用户输入后 C++ 程序崩溃

c - 在C中将PPM从RGB转换为HSL

c - LLVM IR 是一种机器无关语言吗?

c - cs50 Segfau 中的维吉尼亚密码

c++ - 在创建此函数以从 C++ 中的单链表搜索元素时,我在哪里犯了错误?

c - 最终答案为零的方程组

java - 替换双链表中的节点

java - 复制链表...不使用克隆