c - 如果我不将辅助变量声明为全局,则链接列表不起作用
问题描述
我正在编写一个程序来创建一个单链表。我正在使用两个指针变量,其中一个被命名为“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 是一个悬空指针,即它不能被取消引用。尝试将其放入 else 块之前t->next=newnode;
t = start;
while(t->next)
t = t->next;
当您将其声明为全局(或静态工作)时,您会使其记住存储在其中的最后一个值,因此每次它不会以悬空指针启动。
推荐阅读
- vba - 从 VBA 宏 Excek 执行 .exe 文件
- java - 如何检查 Java 应用程序请求的端点
- ios - 按下时禁用按钮 30 秒,再次启用,然后再次按下时禁用
- html - 只有css文件中的某些特定更改会反映在浏览器中
- ethereum - 当`require`评估为false时如何继续执行函数
- nlp - 如何将文本元数据实现为 spacy 输出?
- python - Pygame 中的文本渲染问题
- django - 过滤具有分页的基于类的视图 ListView
- firebase - 如何根据我们得到的随机列表项设置gridView Builder的高度
- python - 随机梯度体面算法的值误差