我目前正在学习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;
}
}
Run Code Online (Sandbox Code Playgroud)
当displayList()打电话给我时,我期望得到这样的东西:
0) - Age = 10
0) - Name = Kiara
1) - Age = GARBAGE
1) - Name = GARBAGE
Run Code Online (Sandbox Code Playgroud)
但是我得到了:
0) - Age = 10
0) - Name = Kiara
1) - Age = 10
1) - Name = Kiara
Run Code Online (Sandbox Code Playgroud)
我在做什么/理解错了吗?
您正在循环中打印节点值,但应打印当前值。节点指针不变。
node->age, node->name
Run Code Online (Sandbox Code Playgroud)
应该:
current->age, current->name
Run Code Online (Sandbox Code Playgroud)