繁体   English   中英

为什么我的程序没有显示任何 output? 0 个错误,0 个警告但没有 output? 我正在使用 Dev C++ 编译器

[英]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); 

这个声明正确吗? 我真的不明白为什么它没有显示 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)

甚至这个 function 也是准确的。 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);

这是您在主 function 中的代码。 在回答问题之前,这里有一些提示给你->

  1. 使用 tab 缩进来提高代码的可读性。
  2. 在你的代码中当你做current->data=90; 或为结构分配一个值,那么您还应该通过current->link = NULLlink指针分配给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);

在上面的代码中,每次赋值后,我将链接指针分配给NULL ,这是一个很好的做法,错误也是如此。

struct node *next=(struct node *)malloc(sizeof(struct node));
next->data=100;
current->link=next;
CountNodes(head);

在上面你没有用任何东西初始化next指针。 所以它包含一些垃圾地址,并且运行一个永无止境的循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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