c - scanf没有在循环C中多次运行
问题描述
所以这是我创建和打印链接列表的代码。我在 atom ide 中编写了这段代码,但是当我运行代码时,询问输入时出现问题,如下面的输出所示。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node {
int data;
struct node *next;
};
struct node * createl(int n);
void printlist(struct node* head2);
int main() {
struct node *mainhead;
int n;
printf("Enter the number of nodes : " );
scanf("%d",&n );
mainhead=createl(n);
printlist(mainhead);
getch();
return 0;
}
void printlist(struct node * head2)
{
struct node *ptr;
ptr=head2;
printf("\nLinked List : \n" );
while (ptr!=NULL) {
printf("%d => ",ptr->data);
ptr=ptr->next;
}
}
struct node * createl(int n)
{
struct node *head=NULL,*iso=NULL,*p=NULL;
int i=0;
while(i<n){
setbuf(stdout,NULL);
iso=(struct node*)malloc(sizeof(struct node));
printf("\nEnter data in node no. %d :",i+1);
scanf("%d",&(iso->data));
iso->next=NULL;
if (head=NULL)
{
head=iso;
} else {
p=head;
while (p->next!=NULL) {
p=p->next;
}
p->next=iso;
}
i++;
}
return head;
}
预期的输出应该是:
Enter number of node : 5
Enter data in node no 1 : 1
Enter data in node no 2 : 2
Enter data in node no 3 : 3
Enter data in node no 4 : 4
Enter data in node no 5 : 5
链表:1 => 2 => 3 => 4 => 5
但它显示的实际输出是:
Enter the number of nodes : 4
Enter data in node no. 1 : 1
program ends
解决方案
代码设置 head
为NULL
应该评估它的时间NULL
:
改变这个
if (head=NULL)//assignment, leaves head NULL when executed
至
if (head==NULL)//evaluates head, but does not change it.
3条补充建议:
当不再需要使用创建
malloc()
的内存时,应该释放它。....
getch();
//free Each node that was created
-
//iso=(struct node*)malloc(sizeof(struct node));
iso=malloc(sizeof(struct node));
getch()
是POSIX
唯一的,并且不是便携式的。一个可移植的替代方法是getchar()
推荐阅读
- vue.js - SCSS 如何加载相对于源文件的样式 url 引用(错误:未找到相关模块)
- javascript - 如何选择具有相同类名的 javaScript 中的所有类?
- c - 在 Windows 10 上的 VSCode 中测试 GLUT 时收到错误消息
- azure - Azure Pipelines YAML - 将变量组用于“部署 Web 应用”azureSubscription 输入时出错
- javascript - 强制 div 溢出而不是调整大小
- android - Android 隐式意图触发媒体播放器,但媒体播放器显示“意图无效”
- javascript - 对body标签的垂直滚动条感到困惑
- .net - 导出 AZURE_STORAGE_CONNECTION_STRING="
" - 命令行失败并且 dotnet 在之后崩溃 - javascript - 使用 Angular 包装的 Jquery 库
- nginx - 用于 Odoo 的 CI/CD 的 Nginx 配置