函数可以返回指向NULL的指针吗?

fre*_*inn 0 c++ nullpointerexception

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;
}
Run Code Online (Sandbox Code Playgroud)

此函数正在查找简单链接列表中的项目,但如果函数找不到它,程序会崩溃告知段违规(我认为这是英文名称).

我想知道是否找到了告诉用户未找到的消息或类似的消息.谢谢.

Ern*_*ill 8

您可能没有向我们展示所有问题代码,但这是一个问题:

while(code != aux->getcode() && aux != NULL){
Run Code Online (Sandbox Code Playgroud)

你正在使用指针"aux",然后测试它是否为NULL.这不好; 你需要反过来做:

while(aux != NULL && code != aux->getcode()){
Run Code Online (Sandbox Code Playgroud)

如果您的指针可能为null,则解除引用之前始终需要检查它.