为什么我们要检查 temp == 是否为空?

Why are we checking if temp == null?

本文关键字:是否 temp 我们 检查 为什么      更新时间:2023-10-16

此代码用于实现链表。

node *single_llist::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node); 
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL; 
return temp;
}
}
  1. 在这里,为什么我们要检查 temp == NULL。我想不出任何可能发生这种情况的情况

  2. 同样要退出 if,为什么我们返回 0,因为返回类型是 node?

  1. 正如消息中明确指出的那样,这是为了防止分配内存的请求失败。 (确切地说,这种情况是如何发生的是无关紧要的;这是可能的,所以代码应该处理它。
  2. 作者假设NULL==0,这通常是正确的,但不一定如此,并且(正如我们似乎都认为的那样(是一个糟糕的假设。