为什么我们要检查 temp == null?
Why are we checking if 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;
}
}
在这里,我们为什么要检查 temp == NULL。我想不出任何情况下会发生这种情况
也是为了退出 if,为什么我们 returning 0 因为 return 类型是节点?
- 正如消息中明确指出的那样,这是为了防止内存分配请求失败。 (确切地 如何 这可能发生是无关紧要的;这是可能的,因此代码应该处理它。)
- 作者假设
NULL==0
,这通常是正确的,但不一定如此,并且(正如我们似乎都认为的那样)是一个错误的假设。
这段代码是链表的实现。
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;
}
}
在这里,我们为什么要检查 temp == NULL。我想不出任何情况下会发生这种情况
也是为了退出 if,为什么我们 returning 0 因为 return 类型是节点?
- 正如消息中明确指出的那样,这是为了防止内存分配请求失败。 (确切地 如何 这可能发生是无关紧要的;这是可能的,因此代码应该处理它。)
- 作者假设
NULL==0
,这通常是正确的,但不一定如此,并且(正如我们似乎都认为的那样)是一个错误的假设。