【问题标题】:LinkedList prints same values [closed]LinkedList 打印相同的值[关闭]
【发布时间】:2019-03-21 11:20:07
【问题描述】:

我目前正在学习 C,但我面临着一个我真的不明白的 Linked List 情况。

我创建了以下程序:

#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

我在做什么/理解错了?

【问题讨论】:

  • 谁说垃圾不能等于10Kiara
  • 没有人,但可能性不大。请参阅下面的答案。

标签: c linked-list


【解决方案1】:

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

node->age, node->name

应该是:

current->age, current->name

【讨论】:

  • 哦,我明白了。谢谢。
【解决方案2】:

在你的循环中:

while ( current != NULL )
{
    printf( "Age = %d\nName = %s\n", node->age, node->name );
    current = current->next;
}

你总是打印node-&gt;name,而它应该是current-&gt;name

 printf( "Age = %d\nName = %s\n", current->age, current->name );

指针node 永远不会改变。

【讨论】:

    【解决方案3】:
    1) - Age = GARBAGE
    1) - Name = GARBAGE
    

    您期望打印垃圾,但不要期望那样。访问未启动的变量实际上是未定义的行为。在大多数实现中,它们会打印垃圾,但实际上任何事情都可能发生(例如运行时崩溃)。即使实现在尝试访问未初始化的变量时没有崩溃,您在打印垃圾时也可能会遇到问题。

    printf("%s", str);
    

    这需要一个以空字符结尾的字符串。如果您的随机垃圾数据不包含\0,那么您将再次遇到运行时崩溃。

    您没有在循环中打印current 的数据(其他答案已经指出)。

    printf( "%d) - Age = %d\n%d) - Name = %s\n",i , current->age, i, current->name );
    

    【讨论】:

    • 我不能给你投票,因为我需要 15 个代表。
    • @Khaled 完全可以,只要你明白我想说的话。
    猜你喜欢
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多