为什么这段代码陷入无限循环?

时间:2018-01-15 00:31:34

标签: c++ data-structures linked-list

为什么head会出现一些随机值?

// Simple insertion at the starting of link list  

#include<iostream>
using namespace std;
struct node{
    int d;
    node *next;
}; // creation of node

node *head=new node; // is there any problem?

void insert(int x)
{
    if (head==NULL) { // is there something wrong?
        head->d=x;
        haad->next=NULL;
    } else {
        node *t=new node;
        t->d=x;
        t->next=head;
        head=t;
    }
}

int main() {
    insert(1);           // function calling
    insert(2);           // function calling
    insert(3);           // function calling
    while(head!=NULL) {
        cout<<head->d<<" ";
        head=head->next;
    } // this is going on to infinity
    return 0;
}

这段代码一直在无穷无尽,我无法理解为什么? 为什么{3} 1后head会出现一些随机值?全球宣布是否有任何问题?

1 个答案:

答案 0 :(得分:1)

head会出现一些随机值,因为列表中的最后一个元素使用next指向随机值。

这最后一个元素是您在此行中创建的第一个节点:

node *head=new node;

通过这样做,您在堆上为此节点分配内存,但是,您没有为节点的字段设置任何值,包括next。然后在循环中,当head指向最后一个节点(首先分配)时,head->next不是NULL,因此循环继续。

三个旁注:

  1. 使用head本身迭代列表元素不是一个好主意,因为你丢失了指向列表头部的指针。
  2. head可以在全球范围内宣布,但通常你应该有充分的理由。在您的程序中,我将在main()中定义它并将其传递给需要它的函数。
  3. 此代码:

    if (head==NULL) { // is there something wrong?
        head->d=x;
        haad->next=NULL;
    

    没有多大意义:它永远不会运行,如果它会 - >&gt;分段错误(因为如果headNULL,则无法引用其字段。

  4. 希望它有所帮助。

相关问题