【发布时间】: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
我在做什么/理解错了?
【问题讨论】:
-
谁说垃圾不能等于
10和Kiara? -
没有人,但可能性不大。请参阅下面的答案。
标签: c linked-list