首页 > 解决方案 > 为什么我的程序没有显示任何输出?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);
}

标签: clinked-list

解决方案


好的,我想我已经在您的代码中找到了错误。


    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 函数中的代码。在回答问题之前,这里有一些提示给你->

  1. 使用 tab 缩进来提高代码的可读性。
  2. 在您的代码中,当您执行current->data=90;或为结构分配值时,您还应该将link指针分配给NULLby current->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用任何东西初始化指针。所以它包含一些垃圾地址,并且运行一个永无止境的循环。


推荐阅读