函数是否可以返回指向 NULL 的指针
Can a function return a pointer to NULL?
class sll_item
{private:
sll_item *next_;
int code_;
...
...
class sll_
{ private:
sll_item *first_;
sll_item *last_;
...
...
sll_item* sll_ :: lookforitem(int code)
{
sll_item* aux = first_;
while(code != aux->getcode() && aux != NULL){
aux = aux->getnext();
}
return aux;
}
此函数正在简单链表中查找项目,但如果该函数找不到它,程序就会崩溃,告诉段违规(我认为这是英文名称(。
我想知道是否找到,告诉用户未找到的消息或类似的东西。谢谢。
您可能没有向我们展示所有的问题代码,但这是一个问题:
while(code != aux->getcode() && aux != NULL){
您正在使用指针"aux",然后测试它是否为 NULL。这不好;你需要反过来做:
while(aux != NULL && code != aux->getcode()){
如果指针可能为 null,则始终需要在取消引用之前检查它。
while(code != aux->getcode() && aux != NULL){
aux = aux->getnext();
}
是的,如果aux
为 NULL,它将崩溃,因为您尝试首先通过编写 aux->getcode()
来获取代码,然后检查aux
是否为 NULL。 也就是说,aux->getcode()
在aux != NULL
之前执行。
现在想想,如果 aux 为 NULL 怎么办? aux->getcode()
会崩溃!
循环应写为:
while(aux != NULL && code != aux->getcode()){
aux = aux->getnext();
}
我认为你应该这样用
while(aux != NULL&&code != aux->getcode())
首先,测试辅助不是 NULL,然后您可以使用 atx->getcode()
.
相关文章:
- 当使用通配符和null指针调用函数时,对输出的说明
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 将位数组转换为 HBITMAP 后 bmBits 的 NULL 指针
- 在访问类的树层次结构中的对象时避免使用 null 指针
- 排序时引用绑定到 'value_type' 类型的 null 指针
- NULL指针解决方案中的C 分割故障
- 取消引用会导致崩溃,即使对于非 NULL 指针也是如此,原因也是如此
- 跟进哈希表 C++,this->next = NULL 指针
- C++中的NULL指针
- 当删除NULL指针(C/C )时,可以保证SegFault
- 引用绑定到类型 'struct value_type' 的 null 指针
- 尝试在C++中使用 NULL 指针时不会发生分段错误
- if(NULL==指针)和if(指针==NULL)之间有什么区别
- 在Linux/GCC下,将NULL指针访问转换为C++异常
- NULL指针检查线程安全
- cppcheck null指针取消引用:m_buffer-否则,针对null进行检查是多余的
- strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记
- Null指针异常(int Vs char)
- 用户定义类中的Null指针无效
- 不是NULL指针,而是错误的访问错误消息