用于检入C的单链表显示

时间:2015-02-04 11:13:19

标签: c

我正在我的计划上实施单链表。现在我有这个显示功能来显示我的单链表中的内容。现在的问题是当我调用我的显示功能时。它只打印头部。例如20-->NULL。用于检查我是否正确实现单链表的显示功能。

struct node
{
    int data;
    struct node *next;
}*start=NULL;

void display()
{
 struct node *new_node;
 printf("The Linked List : ");
 new_node=start;
 while(new_node!=NULL)
   {
   printf("%d--->",new_node->data);
   new_node=new_node->next;
   }
  printf("NULL");
}



void creat(int num)
{
      struct node *new_node,*current;

      new_node=malloc(sizeof(struct node));


      new_node->data=num;
      new_node->next=NULL;

      if(start==NULL)
      {
      start=new_node;
      current=new_node;
      }
      else
      {
      current->next=new_node;
      current=new_node;
      }
      //printf("%d->",new_node->data);
}

void main()
{

    int binrange,max=100,n,i,divi;
    int inp[4];
    clrscr();
    printf("enter 5 numbers: ");
    for(i=0;i<5;i++)
    {
        scanf("%d",&inp[i]);
    }
    printf("\nenter range: ");
    scanf("%d",&binrange);
    n=max/binrange;
    divi=max/n;

    for(i=0;i<=max;i++)
    {
        if(i%divi==0 && i>0)
        {
            //create nodes here
            //store i into nodes
            creat(i);


        }


    }

    display();
    getch();
}

2 个答案:

答案 0 :(得分:1)

在您的代码中,您正在定义

int inp[4];

然后你正在阅读

for(i=0;i<5;i++)
    {
        scanf("%d",&inp[i]);
    }

i为4时,显然超过分配的内存[c中的数组索引从0开始]。所以,undefined behaviour


编辑:

此外,正如Joachim Pileborg先生所提到的,struct node * currentcreat()函数的本地函数,因为每次函数完成时都超出范围。

副作用:

  • 每次开始时都有一个新的current有垃圾[你没有初始化]。
  • 您将取消引用未初始化的内存。

您需要一种存储值的方法。否则,再次,UB。

P.S - 两种情况都以自己的方式引起UB。 : - )

答案 1 :(得分:1)

变量currentcreat函数中的 本地 变量,它超出范围(&#34;消失& #34;)每次creat函数退出。

这意味着两件事:每次调用函数时,变量都将始终未初始化,并且通过取消引用(未初始化的)指针undefined behavior

未定义行为的原因仅仅是因为该变量未初始化。未初始化的非静态局部变量具有不确定值,实际上如果看起来是随机的。所以你正在做的是把这个指针指向&#34;随机&#34;位置并写信给它。

有三种可能的解决方案:一种是使current变量static,另一种是使其成为全局,第三种是根本没有它,每次都找到结束该函数被调用。哦,如果你先选择其中一个,你应该将它重命名为end(或类似的东西),因为它是什么,指向列表末尾的指针。

相关问题