当我运行此代码时,它进入无限循环。我不了解它的行为。请帮助

问题描述:

#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".