本文介绍了解引用空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int* p = 0;
int* q = &*p;

这是未定义的行为或不?我浏览一些相关的问题,但这个具体方面没有显示出来。

Is this undefined behavior or not? I browsed some related questions, but this specific aspect didn't show up.

推荐答案

在这个问题的答案是:这取决于你是以下哪种语言标准: - )

The answer to this question is: it depends which language standard you are following :-).

在C90和C ++,因为你对空指针进行间接(通过执行 * P ),以及这样做,这不是有效的结果不确定的行为。

In C90 and C++, this is not valid because you perform indirection on the null pointer (by doing *p), and doing so results in undefined behavior.

不过,在C99,这个的的有效的,良好的,和明确的。在C99,如果一元的操作数​​ - &安培; 而获得应用一元的结果 - * 或通过执行下标( [] ),那么无论是&安培; 还是 * [] 应用。例如:

However, in C99, this is valid, well-formed, and well-defined. In C99, if the operand of the unary-& was obtained as the result of applying the unary-* or by performing subscripting ([]), then neither the & nor the * or [] is applied. For example:

int* p = 0;
int* q = &*p; // In C99, this is equivalent to int* q = p;

同样,

int* p = 0;
int* q = &p[0]; // In C99, this is equivalent to int* q = p + 0;

从C99§6.5.3.2/ 3:

From C99 §6.5.3.2/3:

如果操作数[的一元&安培; 运算符]是一元 * 运算符的结果,无论是该运营商也不是&放大器; 运营商进行评估,其结果是,如果两者都省略了,除了对经营者的约束仍然适用,其结果不是左值

同样的,如果操作数是 [] 运算符的结果,无论是&安培; 运营商,也不是一元 * 由隐含的 [] 进行评估,其结果是,如果在 &安培; 运营商被拆除,并在 [] 运营商都改为 + 运营商。

Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.

(和它的注脚,#84):

(and its footnote, #84):

因此​​,&放大器; * E 等同于电子(即使电子是一个空指针)

这篇关于解引用空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:30