指针,*运算符

问题描述 投票:0回答:3

*运算符如何在此示例中工作,为什么它可以工作?

int *p, x, y;
x = 5;
p = &x; // stores the address of x in p;
y = *p; // the * operator gets the value stored at the address stored in p. Now y is 5;
*p = 0; // why does this work? Shouldn't it be as writing 5 = 0? since the * operator gets the value stored at that address?

为什么* p = 0将0分配给x?我已经对代码进行了评论,以便更好地理解我在这里缺少的内容。

谢谢!

c pointers
3个回答
8
投票

当你写*p时,它不仅仅意味着“在p指向的位置获取值”。它是一个表达式,C中的表达式具有两个值类别之一。他们是非正式的左撇子和右撇子。粗略地说,L和R表示表达式出现在赋值的哪一侧。左值可能出现左边(并且“被分配给”),而左值可能不出现。

例如,如果你有这个(为了简洁而简称)代码片段:

struct point { int x; int y;};
struct point p;
p.x = p.y = 1;

然后p.xp.y都是左值表达式。所以可以分配给。同样,指针间接给我们一个左值。我们甚至可以在C语言标准中看到它:

6.5.3.2地址和间接运算符 - p4

一元*运算符表示间接。如果操作数指向函数,则结果是函数指示符;如果它指向一个对象,则结果是指定该对象的左值。如果操作数的类型为''指向类型'',则结果的类型为''type''。如果为指针分配了无效值,则unary *运算符的行为未定义。


0
投票

因为指针存储变量的地址..所以在你的代码中* P的地址为x ...假设地址x = 23,地址y = 24,因为p是指针,那么p的地址相当于地址x是23

x=5;// stores 5 in the address 23
p =&x //it has an address of x which is 23
y= *p // so gets the value 5 as you told

*p = 0// now stores the value 0 in the address 23. as x is  having address 23 automatically x value changes to zero

0
投票

因为指针p的地址为x

© www.soinside.com 2019 - 2024. All rights reserved.