gpt4 book ai didi

c - 一元 & 运算符遇到 [] 时的行为

转载 作者:行者123 更新时间:2023-12-02 19:40:37 25 4
gpt4 key购买 nike

我一直在阅读 C11 6.5.3.2 p3

The unary & operator yields the address of its operand. If the operand has type “type”, the result has type “pointer to type”. If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue. 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. Otherwise, the result is a pointer to the object or function designated by its operand.

尽管反复阅读,我还是无法理解这一段的大部分内容。
我的问题部分是 [] 隐含的 *,[] 运算符更改为 + 运算符此操作数指定的函数。本段讲的是&,但是为什么在说[]之后出现*,并且出现术语“指定功能”。并且 [] 运算符更改为 + 运算符 似乎试图说出数组的定义: E1[E2] = *((E1) + (E2)) 是什么这些行是什么意思?我需要一些帮助。

最佳答案

If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.

一元 &应用于一元 * 的结果,取消*并转换原始*的操作数到右值:

#include <assert.h>
int main()
{
int *p=&(int){42};
assert(&*p == p); //the value (42) is not fetched from the target
#if 0
&*p = &(int){1000}; //not OK; & cancels the * but converts p to an r-value (can't be on the left-hand side of an assignment)
#endif
p = &(int){1000}; //ok; p is an l-value (can be on the left hand side of an assignment)
//(more accurately: can have its address taken)
}

现在自从 pointerOrArray[index]表达式定义 ( 6.5.2.1p2 ) 为 *(pointerOrArray+index) (一元 * 的结果,除了 * 被隐藏),您可以对其应用相同的规则: &pointerOrArray[index] <=> (pointerOrArry+Index) 。这就是你引用的第一句话所说的。

您引用的最后一句话可以(在 6.5.3.2p3 的上下文中)解释为:

否则(如果一元 & 未与 *[] 组合),结果(一元 & )是指向对象 ( &object ) 或函数 ( &function ) 的指针)由其操作数( objectfunction )指定。

关于c - 一元 & 运算符遇到 [] 时的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60247975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com