c++ - 我们为什么要检查 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,为什么我们返回0,因为返回类型是节点?
解决方案
- 正如消息中明确指出的那样,这是为了防止分配内存的请求失败。(这究竟是如何发生的无关紧要;有可能,所以代码应该处理它。)
- 作者假设
NULL==0
,这通常是正确的,但不一定如此,并且(正如我们俩似乎都认为的那样)是一个不好的假设。
推荐阅读
- javascript - 网络抓取:某些数据(图像)似乎无法抓取?
- powershell - Azure RM 和 Powershell(服务名称)
- python-3.x - 当使用 QuTiP 绘制相干态的 Wigner 函数时,出现了奇怪的图案
- android - 使用 Braintree Drop-In UI 集成 Google Pay
- winapi - 如何使用 MFC 或 GDI 或 GDI+ 为位图中的所有像素设置 alpha 值
- vba - 在表格 VBA Powerpoint 中查找字符串
- java - 如何从 Jboss EAP 6.4 中部署的所有战争的 manifest.mf 文件中获取实现版本详细信息
- typescript - 基于 TypeScript 中的现有对象创建 TypeSafe 对象字面量
- c++ - 如何配置 Doxygen 以在“类索引”中包含类的 typedef?
- curl - HTTP_PROXY 不工作