C 列出链表时的无限循环

C 列出链表时的无限循环,c,C,问题在while循环中出现。我找不到出什么问题了 #include <stdio.h> #include <stdlib.h> #include <conio.h> typedef struct node { int data; node *next; }; int main(){ node * root= (node *) malloc(sizeof(node)); node * temp = root

问题在while循环中出现。我找不到出什么问题了

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

typedef struct node {
        int data;
        node *next;
        };

int main(){
 node * root= (node *) malloc(sizeof(node));
 node * temp = root;
 for(int i=0;i<10;i++){
         temp->data=i*10;
         temp->next=(node *) malloc(sizeof(node));
         temp=temp->next;
         }     
 temp =root;
 while(temp){ //infinite loop
         printf("\n%d",temp->data);
         temp=temp->next;       
         }
         getch();
    return 0;
}    
#包括
#包括
#包括
类型定义结构节点{
int数据;
节点*下一步;
};
int main(){
node*root=(node*)malloc(sizeof(node));
节点*temp=root;
对于(int i=0;idata=i*10;
temp->next=(node*)malloc(sizeof(node));
温度=温度->下一步;
}     
温度=根;
while(temp){//无限循环
printf(“\n%d”,临时->数据);
温度=温度->下一步;
}
getch();
返回0;
}    

您可能缺少列表构建循环中的最后一行:

    /* ... */
    temp->next = NULL;
}

您可能缺少列表构建循环中的最后一行:

    /* ... */
    temp->next = NULL;
}

您从未将最后一个节点设置为null。Put
temp->next=NULL;

在for循环之后


使用malloc分配节点时,值不会初始化为任何值。因此
next
指向内存中的某个随机位置。

您从未将最后一个节点设置为null。Put
temp->next=NULL;

在for循环之后


当您使用malloc分配节点时,值不会初始化为任何值。因此
next
指向内存中的某个随机位置。

当您分配最后一个节点时,您从未设置其
next
指针。由于未初始化,它将包含该内存位置中已经存在的任何数据,几乎可以肯定是not NULL。在处理
while
循环中的所有节点后,程序将取消引用此未初始化指针并调用未定义的行为。

分配最后一个节点时,您从未设置其
下一个
指针。由于未初始化,它将包含该内存位置中已存在的任何数据,而ch几乎肯定不是NULL。在处理
while
循环中的所有节点后,程序将取消引用此未初始化指针并调用未定义的行为。

您确定要编译
C

在for循环中,将
next
指针初始化为NULL

for (int i = 0; i < 10; i++) {
    /* ... */
    temp->next = malloc(sizeof (node));
    assert(temp->next && "no memory"); /* easy test of malloc return value */
    temp->next->next = NULL;
    /* ... */
}
for(int i=0;i<10;i++){
/* ... */
temp->next=malloc(sizeof(node));
assert(temp->next&&“无内存”);/*轻松测试malloc返回值*/
临时->下一步->下一步=空;
/* ... */
}

您确定要编译
C

在for循环中,将
next
指针初始化为NULL

for (int i = 0; i < 10; i++) {
    /* ... */
    temp->next = malloc(sizeof (node));
    assert(temp->next && "no memory"); /* easy test of malloc return value */
    temp->next->next = NULL;
    /* ... */
}
for(int i=0;i<10;i++){
/* ... */
temp->next=malloc(sizeof(node));
assert(temp->next&&“无内存”);/*轻松测试malloc返回值*/
临时->下一步->下一步=空;
/* ... */
}

这是因为
while(temp)
始终包含一个值。
确保最后一个节点指向空值,这样
temp=temp->next;
将返回空值并退出循环。

这是因为
while(temp)
始终包含一个值。
确保您的最后一个节点指向空值,这样
temp=temp->next;
将返回空值并退出循环。

无限循环还是挂起?(我猜是后者)--您的最终temp->next未定义,可能会将您的程序发送到暮光之区I,我是唯一喜欢“无限循环”概念的人?无限循环还是挂起?(我猜是后者)--您的最终temp->next未定义,可能会将您的程序发送到暮光之城我是唯一喜欢“无限循环”概念的人?在回路内部。在malloc测试之后。上面的三条线应保持在一起。在回路内部。在malloc测试之后。上面的三条线应保持在一起。