函数是否可以返回指向 NULL 的指针

Can a function return a pointer to NULL?

本文关键字:NULL 指针 返回 是否 函数      更新时间:2023-10-16
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() .