C LinkedList打印相同的值
我目前正在学习C,我面临着一个链表的情况,我真的不理解它 我创建了以下程序:C LinkedList打印相同的值,c,linked-list,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 ) {
#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;
}
}
但我得到的却是:
0) - Age = 10
0) - Name = Kiara
1) - Age = 10
1) - Name = Kiara
我在这里做什么/理解错误?您正在循环中打印节点值,但应该打印当前值。节点指针不会更改
node->age, node->name
应该是:
current->age, current->name
在您的循环中:
while ( current != NULL )
{
printf( "Age = %d\nName = %s\n", node->age, node->name );
current = current->next;
}
您总是打印节点->名称
,而它应该是当前->名称
:
printf( "Age = %d\nName = %s\n", current->age, current->name );
指针节点
从不更改
1) - Age = GARBAGE
1) - Name = GARBAGE
你期望垃圾会被打印出来,但不要期望这样。访问未初始化的变量实际上是未定义的行为。在大多数实现中,它们打印垃圾,但实际上任何事情都可能发生(例如运行时崩溃)。即使实现在尝试访问未初始化的变量时没有崩溃,您也可能在打印垃圾时遇到问题
printf("%s", str);
这需要一个以null结尾的字符串。如果您的随机垃圾数据不包含\0
,则再次出现运行时崩溃
您没有在循环中打印当前的数据(其他答案已经指出)
谁说垃圾不能等于
10
和Kiara
?没有人,但可能性不大。看下面的答案。哦,我明白了。谢谢。我不能投你一票,因为我需要15个代表。只要你明白我想说的话,那就好了。
printf("%s", str);
printf( "%d) - Age = %d\n%d) - Name = %s\n",i , current->age, i, current->name );