为什么 *(&identifier)=value 在 C 中有效?
Why does *(&identifier)=value works in C?
例如,
int x = 10;
*(&x) = 20;
printf("%d \n",x); // output is 20
根据 ISO C11-6.5.3.2 第 4 段,
The unary * operator denotes indirection. If the operand points to a
function, the result is a function designator; if it points to an
object, the result is an lvalue designating the object. If the operand
has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an
invalid value has been assigned to the pointer, the behavior of the
unary * operator is undefined.
由于操作数 &x
既不是函数指示符也不是对象指示符(它是一个指向 int 类型的指针),我预计会有未定义的行为,但它工作得很好!我错过了什么?
运算符&x
表示变量x
的地址。前面加星号表示变量x
地址处的内容,就是x
.
运算符 *
和 &
相互抵消,当这样使用时。
让我为您解析:
int x = 10;
*(&x) = 20;
*
== 星号运算符
&x
== 操作数(星号运算符的)
If the operand points to a function, the result is a function
designator; if it points to an object, the result is an lvalue
designating the object.
操作数(&x == address of x where x is an int)指向一个int类型的对象。
=> 结果是指定 x(x==对象)的左值。
If the operand has type ‘‘pointer to type’’, the result has type
‘‘type’’.
操作数的类型为 指向 int 的指针,因此结果的类型为 int。
例如,
int x = 10;
*(&x) = 20;
printf("%d \n",x); // output is 20
根据 ISO C11-6.5.3.2 第 4 段,
The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.
由于操作数 &x
既不是函数指示符也不是对象指示符(它是一个指向 int 类型的指针),我预计会有未定义的行为,但它工作得很好!我错过了什么?
运算符&x
表示变量x
的地址。前面加星号表示变量x
地址处的内容,就是x
.
运算符 *
和 &
相互抵消,当这样使用时。
让我为您解析:
int x = 10;
*(&x) = 20;
*
== 星号运算符&x
== 操作数(星号运算符的)
If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.
操作数(&x == address of x where x is an int)指向一个int类型的对象。
=> 结果是指定 x(x==对象)的左值。
If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’.
操作数的类型为 指向 int 的指针,因此结果的类型为 int。