为什么p && *p
防止空指针取消引用?
如何使用表达式来防止取消引用?
最佳答案
来自 C 标准#6.3.2.3p3
3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
...
...Footnotes
66) The macro NULL is defined in (and other headers) as a null pointer constant; see 7.19.
逻辑AND
操作expr1 && expr2
采用短路行为。通过逻辑短路,第二个操作数 expr2
,仅当结果未完全由第一个操作数 expr1
确定时才求值。
即expr2
如果 expr1
则不进行评估符合逻辑0
(错误)。
如果p
是 NULL
指针,那么它将被评估为 0
并且由于 &&
的短路行为运算符(operator)*p
不会被评估。就是这样p && *p
防止空指针取消引用。
关于c - 防止空指针解除引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058879/