【问题标题】:Assign struct pointer to a struct pointer inside of null struct pointer [duplicate]将结构指针分配给空结构指针内的结构指针[重复]
【发布时间】:2018-11-18 17:09:26
【问题描述】:

这个问题可能很愚蠢,但我一直想知道如果你有:

struct List {
    int x;
    List *next;
};
struct List *start = nullptr;
struct List *tmp = start->next; 

tmp 会发生什么?

我已经尝试编译它,我没有收到任何错误。如果我输出start 的地址,我得到0,但如果我输出tmp,我什么也得不到。

【问题讨论】:

  • 你取消引用一个空指针(开始),所以你有未定义的行为。在你完成start->next 之后,你就无法对你的程序进行推理了。
  • 应该是空指针访问。我不知道你怎么没有得到运行时错误!
  • @Mukesh 未定义的行为不能保证运行时错误。
  • 但可能会发生分段错误。
  • @Ebrahim 任何事情都可能发生。或者什么都没有。

标签: c++


【解决方案1】:

在线 struct List *tmp = start->next; 因为我们知道 start == nullptr 您正在取消引用 nullptr 值。这是 UB(未定义行为),因此“任何事情”都可能发生。

【讨论】:

    【解决方案2】:

    这是一种未定义的行为。多次执行后,它可能会输出不同的结果或分段错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2019-06-26
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多