【发布时间】:2020-03-06 15:23:45
【问题描述】:
我正在编写一个程序来创建一个单链表。我正在使用两个指针变量,其中一个被命名为“start”,它指向列表的第一个节点,另一个我正在使用的指针变量被命名为“t”。我将此指针用作辅助变量,它有助于在不影响开始的情况下遍历列表。
该程序已成功编译,但我面临的问题是在运行时它只允许我将一个节点添加到列表中。之后,如果我尝试添加另一个节点,则在输入该节点的数据后执行停止。
我尝试了几件事,但只有一个有效。如果我将“辅助指针变量”声明为全局,则程序开始运行良好。
为什么会发生这种情况?
我只在函数中使用辅助指针变量“t”来遍历列表,它甚至没有与程序中的另一个函数通信。
有人能解释一下为什么它只适用于全局声明吗?
这是函数的代码->
void insert()
{
struct node *newnode;
struct node *t; //<------this is the helper variable if I declare this locally
//then the problem occurs in the run time.
newnode = create();
printf("Enter data ");
scanf("%d",&newnode->info);
//printf("Node info = %d",newnode->info);
if(start==NULL)
{
start=newnode; <------ this is that start variable which is declared above globally
start->next=NULL;
t=newnode;
}
else
{
t->next=newnode;
t=newnode;
t->next=NULL;
}
printf("%d successfully added to the list.",newnode->info);
}
【问题讨论】:
-
遇到
t->next=newnode;这行,t指向哪里? -
请创建一个minimal reproducible example。这包括提供导致所描述问题的示例输入。
-
在“t->next=newnode;”结构体中的“next”指针开始指向最新创建的节点
标签: c pointers data-structures linked-list global-variables