C 指针,*运算符

C 指针,*运算符,c,pointers,C,Pointers,在本例中,*运算符是如何工作的,为什么工作 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

在本例中,*运算符是如何工作的,为什么工作

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?我对代码进行了注释,以便更好地理解我在这里缺少的内容


谢谢大家!

因为指针存储变量的地址。。 所以在你的代码中,P的地址是x。。。 假设x=23的地址,y=24的地址,因为p是指针,所以p的地址等于x的地址,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

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

例如,如果您有以下代码(为简洁起见进行了压缩):

struct point { int x; int y;};
struct point p;
p.x = p.y = 1;
然后
p.x
p.y
都是左值表达式。因此可以分配给。同样,指针间接寻址也给了我们一个左值。我们甚至可以看到它在C语言标准中的表述:

6.5.3.2地址和间接运算符-p4

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


因为指针‍‍
p
的地址为
x

*p指的是存储在p中的地址的值,该地址的值为x,因此当您看到类似
int x=5的内容时,*p=0类似于x=0;x=0您是否也将其解释为
5=0
?如果不是,为什么你认为
*p=0
不同吗?
*p
的行为与
x
完全相同,解释得很好,但考虑到他提出的问题,可能对OP来说太高级了……@LoPiTaL-我尽量保持非正式和直观(直到最后,我忍不住添加了标准引用)。你认为有些事情可以进一步简化吗?我现在明白了。我以为它只会从地址中获取值。现在一切都清楚了。非常感谢。其他人不太明白这个问题。@AMayer-很乐意帮忙:)