下面展示下 错误代码。
// 错误是在这里head->next==NULL
struct ListNode* oddEvenList(struct ListNode* head){
if(head->next==NULL){
return head;
}
为什么会提示runtime error: member access within null pointer of type ‘struct ListNode’?
明明我没有访问空指针,为什么说我访问空指针?
当我把
head->next==NULL改成
head == NULL
就解决问题了
原因应该是运行时,先访问了head,判断了head是否为空,若head为空,则head->next就是访问了空指针,所以改成head==NULL,就避免了这种可能。
本文探讨了一段C++代码中出现的runtimeerror: member access within null pointer of type 'struct ListNode'的问题。作者指出,错误源于在检查head->next是否为NULL之前就尝试访问head,导致可能的空指针异常。通过将条件语句从head->next==NULL改为head==NULL,解决了这个问题,确保在访问head->next之前已确认head不为空。
2万+

被折叠的 条评论
为什么被折叠?



