<分区>
我目前正在学习 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
我在这里做什么/理解错了什么?