[英]Why is my program not showing any output? 0 errors, 0 warnings but no output? I'm using Dev C++ compiler
#include<stdio.h>
#include<stdlib.h
struct node{
int data;
struct node *link;
};
void CountNodes(struct node *head);
Is this declaration correct?这个声明正确吗? I really don't understand why it's not showing output.我真的不明白为什么它没有显示 output。
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)
Even this function is accurate.甚至这个 function 也是准确的。 It was working just 10 min ago but now it's not. 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);
}
Ok, I think I have found the bug in your code.好的,我想我已经在您的代码中找到了错误。
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);
It is your code in main function.这是您在主 function 中的代码。 Before answering the question here are some tips for you->在回答问题之前,这里有一些提示给你->
current->data=90;
在你的代码中当你做current->data=90;
or assign a value to the struct then you should also assign the link
pointer to NULL
by current->link = NULL
and this is why there is a bug in your code.或为结构分配一个值,那么您还应该通过current->link = NULL
将link
指针分配给NULL
,这就是代码中存在错误的原因。When I ran your code on my system then it ran in an infinite loop.当我在我的系统上运行您的代码时,它会在无限循环中运行。 So the upgraded code for you program is ->所以你程序的升级代码是 ->
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);
In the above code after each assigning of value, I'm assign the link pointer to NULL
which is a good practice and the bug was this too.在上面的代码中,每次赋值后,我将链接指针分配给NULL
,这是一个很好的做法,错误也是如此。
struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
CountNodes(head);
Here above you have not initialized next
pointer with anything.在上面你没有用任何东西初始化next
指针。 So it is containing some Garbage Address and this running a loop that never ends.所以它包含一些垃圾地址,并且运行一个永无止境的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.