当我运行此代码时,它进入无限循环。我不了解它的行为。请帮助 [英] When I Run This Code, It Goes Into Infinite Loop.I Don't Understand Its Behaviour. Pls Help

查看:104
本文介绍了当我运行此代码时,它进入无限循环。我不了解它的行为。请帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

struct linked
{
    int data;
    struct linked *next;
};

void main()
{
    struct linked *newnode=(struct linked *)malloc(sizeof(struct linked));
    struct linked *root=NULL;
    struct linked *current;
    int i=0;
    
    clrscr();
    
    while(i<=10)
    {
        newnode->data=i;
        newnode->next=NULL;
        if(root==NULL)
        {
            root=newnode;
            current=root;
        }
        else
        {
            current->next=newnode;
            current=newnode;
        }
        i++;
    }
    current=root;
    while(current!=NULL)
    {
        printf("%d\n",current->data);
        current=current->next;
    } 
    getch();
}

推荐答案

但是你能告诉我在while循环之外的那个分配的实际错误是什么?



简单:正如理查德所说,你只分配一个节点。



这意味着所有节点指针(root,current,newnode和newnode-> next)都指向同一个地方:唯一的节点。

所以当你到达你的printf循环时,你每次都按照下一个节点指针回到同一节点 - 你根本无法达到空值,因为没有一个!

你想要做的是:

"But can you tell me what was the actual fault with that allocation outside the while loop?"

Simple: As Richard says, you only allocate one node.

Which means that all your node pointers (root, current, newnode, and newnode->next) all point to the same place: the one and only node.
So when you get to your printf loop, you follow the next node pointer back to the same node each and every time - you cannot reach a null at all, because there isn't one!
What you want to do is:
while (still creating nodes)
   {
   allocate new node
   set new node next to null
   set current next node to new node
   set current to new node
   }





别忘了清理身后并释放你分配的内存!它在这里并不重要,但如果你不这样做,它会导致真实代码中的大量(并且非常难以追踪)问题 - 它被称为内存泄漏。



Don't forget to clean up behind you and release the memory you allocated! It's not critical here, but it leads to enormous (and very hard to track down) problems in "real" code if you don't - it's called a "memory leak".


这篇关于当我运行此代码时,它进入无限循环。我不了解它的行为。请帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆