【问题标题】:Linked List In Data Structures数据结构中的链表
【发布时间】:2015-08-12 14:40:16
【问题描述】:

假设temp 是一个指向结构node 的指针。 temp->nextNULL。那么temp->next->next 的值是多少呢?

简而言之,NULL->next 的值是多少?它是否依赖于编译器,因为我在 ubuntu 和代码块(windows)中看到了不同的结果?

下面程序的输出是什么?

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

 main()
 {
   struct node *temp,*p;
   int c=0;
   temp=(struct node *)malloc(sizeof(struct node));
   temp->data=50;
   temp->next=NULL;
   p=temp;
   if(p->next->next==NULL)//will it enter the if loop?
      c++;
   printf("%d",c);
  }

【问题讨论】:

  • 在评估 IF 条件时应该抛出一个段错误。
  • 不一定。特别是在 Windows 中,没有段错误......这是一种未定义的行为。例如,它可以炸毁月球,所以请不要这样做。我们仍然需要它。
  • 我投票结束这个问题,因为它是另一个“我知道它是 UB,但我仍然希望 SO 贡献者在它上面浪费时间”

标签: c linked-list


【解决方案1】:

NULL->next 必须给你一个段错误。

你可能想要这样的东西:

if(p->next != NULL && p->next->next==NULL)

if(p->next == NULL || p->next->next==NULL)

【讨论】:

    【解决方案2】:

    如果 temp->next 为 NULL,则取消引用以获取 temp->next->nextundefined behavior。可能会发生崩溃,但可能会发生其他事情。原则上,任何事情都可能发生。

    不要取消引用空指针。

    【讨论】: