leetcode_member access within null pointer of type 'struct ListNode'

 

 空指针引用问题,最近经常遇到这个bug,找出了出现此bug的一个原因:

不能引用没有被赋值的指针。

例如:

int *q=p->next;

 

要改为:

 

if(p){

 int *q=p->next;

}

要使用指针p,必须保证p不为空指针。

 

更具体地,再举一个例子:

#include <iostream>

using namespace std;

int main()
{
     int *p=nullptr;
     int a=100;
     *p=a;
     cout<<*p<<"\n";
     return 0;
}

这个代码是不通过的,p是空指针,不能对其操作;

而:

#include <iostream>

using namespace std;

int main()
{
     int *p=nullptr;
     int a=100;
     p=&a;
     cout<<*p<<"\n";
     return 0;
}

是通过的,p刚开始是空指针,后被赋值为a的地址,因此不是空指针了,因此最后输出为100.

附上一个详解指针的blog,里面的第五点:NULL和指针void 也提到了这一点:

https://blog.csdn.net/xierhacker/article/details/52516742

posted @ 2021-06-15 13:19  SanFranciscoo  阅读(660)  评论(0编辑  收藏  举报