c - 为什么我的程序没有显示任何输出?0 个错误,0 个警告但没有输出?我正在使用 Dev C++ 编译器
问题描述
#include<stdio.h>
#include<stdlib.h
struct node{
int data;
struct node *link;
};
void CountNodes(struct node *head);
这个声明正确吗?我真的不明白为什么它没有显示输出。
int main()
{
struct node *head=(struct node *)malloc(sizeof(struct node));
head->data=45;
struct node *current=(struct node *)malloc(sizeof(struct node));
current->data=90;
head->link=current;
struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
CountNodes(head);
}
void CountNodes(struct node *head)
甚至这个函数也是准确的。10 分钟前它还在工作,但现在不行了。
{
int count=0;
if(head==NULL)
{
printf("Linked list is empty!");
}
struct node *ptr=NULL;
ptr=head;
while(ptr!=NULL)
{
count++;
ptr=ptr->link;
}`enter code here`
printf("%d",count);
}
解决方案
好的,我想我已经在您的代码中找到了错误。
struct node *head=(struct node *)malloc(sizeof(struct node));
head->data=45;
struct node *current=(struct node *)malloc(sizeof(struct node));
current->data=90;
head->link=current;
struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
CountNodes(head);
这是您在 main 函数中的代码。在回答问题之前,这里有一些提示给你->
- 使用 tab 缩进来提高代码的可读性。
- 在您的代码中,当您执行
current->data=90;
或为结构分配值时,您还应该将link
指针分配给NULL
bycurrent->link = NULL
,这就是代码中存在错误的原因。
当我在我的系统上运行您的代码时,它会在无限循环中运行。所以你程序的升级代码是 ->
struct node *head=(struct node *)malloc(sizeof(struct node));
head->data=45;
head->link = NULL;
struct node *current=(struct node *)malloc(sizeof(struct node));
current->data=90;
current->link = NULL;
head->link=current;
struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
next->link = NULL;
CountNodes(head);
在每次分配 value 之后的上述代码中,我都分配了链接指针,NULL
这是一个很好的做法,错误也是如此。
struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
CountNodes(head);
在上面你没有next
用任何东西初始化指针。所以它包含一些垃圾地址,并且运行一个永无止境的循环。
推荐阅读
- python - 在字符串中查找最长的数字子序列
- reactjs - 如何使用带有现有按钮的 react material-ui 快餐栏?
- python - 如何通过 Python Scrapy 蜘蛛解析嵌入的链接
- java - 为什么使用 ClassLoader 读取资源
- android - Android“未安装应用程序”错误 - 无法删除 .tmp 文件
- python - 强制单击突出显示按钮但不单击它?- 蟒蛇硒
- mysql - ERROR 1093 (HY000): 您不能在 FROM 子句中指定目标表 `article` 进行更新
- c# - IdentityServer4、本地 API、外部 REST 客户端
- angular - 无法从 Promise 的 Typescript / Angular 10 调用类函数
- c - 创建一个不强制转换的 sockaddr