c - 防止空指针解除引用

标签 c null-pointer

为什么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 (错误)。

如果pNULL指针,那么它将被评估为 0并且由于 && 的短路行为运算符(operator)*p不会被评估。就是这样p && *p防止空指针取消引用。

关于c - 防止空指针解除引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058879/

相关文章:

c++ - C++中的空指针声明混淆

c - C 中 free() 的确切输出?

java - 如何避免可能的空指针取消引用

java - 多线程访问同一个文本文件

c++ - NULL 是有效的 FILE* 吗?

java - Android - 空指针异常

c++ - 限制指针算术或比较的基本原理是什么?

c++ - 为什么在 OpenGL 中显式管理矩阵更好?

c - 我正在尝试写入寄存器 hi 的某些位以启动电源模式进入休眠状态

c - 如何对c中文件中存储的数据进行排序