简体   繁体   中英

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.

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. It was working just 10 min ago but now it's not.

{
    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. Before answering the question here are some tips for you->

  1. Use tab Indentation to improve the readability of code.
  2. In your code when you do 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.

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.

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. So it is containing some Garbage Address and this running a loop that never ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM