检查指针是否为NULL并导致运行时错误

luo*_*uan 0 c++ pointers

我正在做leetcode问题https://leetcode.com/problems/add-two-numbers/

ListNode的定义是:

 // Definition for singly-linked list.
 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };
Run Code Online (Sandbox Code Playgroud)

当我检查列表是否结束时,我使用了:

int v1 = h1 == NULL? h1->val:0; // h1 is defined before: ListNode* h1 = l1;
Run Code Online (Sandbox Code Playgroud)

但它返回运行时错误,但如果我将其更改为

int v1 = h1? h1->val:0;
Run Code Online (Sandbox Code Playgroud)

它被接受了.

这是为什么?

Bil*_*nch 10

这行代码:

 int v1 = h1 == NULL ? h1->val : 0;
Run Code Online (Sandbox Code Playgroud)

或多或少相同:

int v1 = 0;
if (h1 == NULL)
    v1 = h1->val;
Run Code Online (Sandbox Code Playgroud)

请注意,如果h1 == NULL,则在以下行中取消引用时将显示未定义的行为h1.