取消引用指针是指向变量的别名还是它只是访问变量的值?

Is dereferencing a pointer an alias for the pointed variable or does it just access the value of the variable?

我无法完全理解取消引用运算符的性质。取消引用只是指向变量的别名还是获取变量的值。

我们知道常量做&constant是无效的,因为常量没有自己的内存。
现在假设我们有这样的东西-


int i=5;

int *ptr=&i;

然后如果我们这样做 &(*ptr) 那么它会如何在较低级别发生?

我心里有两三件事让我带你去全部。

案例 1: 我读到 *ptr 给出了该内存位置的值,因此请记住 &(*ptr) 将计算为 &5 但是这会出错,因为 5 是一个常数。

情况2:*ptr只是变量'i'的别名那么&(*ptr)就会变成&i并且这对我来说很好。

案例 3: 我被告知 &* 在表达式 &(*ptr) 中相互抵消了,但我不是能够得到它。它们是如何相互抵消的?

它确实是第二种情况。作为指向本地堆栈变量的指针,&(*ptr) 将获得它的地址。

常量变量的记忆方式与non-constants相同。但如果它不以任何方式操纵它们的内存地址,优化器可能会将其分割出来并放入常量值 just-in-place.

在 C 标准中:

A.7.4.3 Indirection Operator The unary * operator denotes indirection, and returns the object or function to which its operand points. It is an lvalue if the operand is a pointer to an object of arithmetic, structure, union, or pointer type. If the type of the expression is ``pointer to T,'' the type of the result is T.

所以,*ptr 将 return 一个左值而不是存储在 i 中的值(所以,说它 return 是一个别名是正确的)。 & 运算符可以用在这个左值上,你得到的结果与 &i 使用 &(*ptr).

得到的结果相同

那么,就是情况2

并且,对于说 &* 相互抵消,正如我们在上面看到的,&(*ptr) 将计算出与 &i 相同的结果,即与 ptr 相同。所以,最后的结果,你可以说,它们相互抵消了。但是,除非编译器决定进行一些优化并删除 &*,否则首先对 *ptr 求值,然后 & 对该结果进行运算。