首页 > 解决方案 > 我们为什么要检查 temp == null ?

问题描述

此代码用于实现链表。

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,因为返回类型是节点?

标签: c++data-structureslinked-liststructuredynamic-memory-allocation

解决方案


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

推荐阅读