[英]Pointers in C, simple doubts
I'm trying to understand some basic principles of pointers. 我试图理解一些指针的基本原理。 Someone told me that assigning value to a pointer variable will change the actual variable value.
有人告诉我,将值分配给指针变量将更改实际变量值。 Is that true?
真的吗? I wrote a piece of code and got this:
我写了一段代码并得到了:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x=5;
int *address_of_x = &x;
int y = *address_of_x;
*address_of_x = 9;
printf("The value of x is: %d\n", x);
printf("The X is at: %p\n", &address_of_x);
printf("value of y = %d\n", y);
return 0;
}
and got the output like this: 并得到这样的输出:
The value of x is: 9
The X is at: 0028FF04
value of y = 5
why the value of "y" stayed 5? 为什么“ y”的值保持5? Is that because of the ordering of commands?
那是因为命令的顺序吗?
Yes, it is. 是的。
address_of_x
is assigned a pointer to x
, but y
is a completely independent int
variable. address_of_x
被分配了一个指向x
的指针,但是y
是一个完全独立的int
变量。 You assign it the same value as x
(through a pointer), but x
and y
are different variables. 您为它分配了与
x
相同的值(通过指针),但是x
和y
是不同的变量。
At this point, assigning to *address_of_x
will change the value of x
, but not y
. 此时,分配给
*address_of_x
将更改x
的值,但不会更改y
。
y
isn't a pointer, it is an integer. y
不是指针,而是整数。 This line: 这行:
int y = *address_of_x;
basically says "take the value pointed to by address_of_x
and copy it into y
. 基本上说:“获取
address_of_x
指向的值并将其复制到y
。
If you had instead done this: 如果您改为这样做:
int *y = address_of_x;
Then *y
would be 9
. 那么
*y
将是9
。
Yes that was because of the ordering of the commands when int y = *address_of_x;
是的,这是因为
int y = *address_of_x;
时命令的顺序int y = *address_of_x;
this executed the 'address_of_x' contained 5
and hence y
got that value 这执行了包含
5
的'address_of_x'并且因此y
得到了那个值
+--------------+
| 5 |
|*address_of_x |
+--------------+
^
| y=*address_of_x =5
|
+--------------+
| address_of_x |
| 0028FF04 |
+--------------+
Next time 下次
*address_of_x = 9
+--------------+
| 9 |
|*address_of_x |
+--------------+
^
| but y still 5
|
+--------------+
| address_of_x |
| 0028FF04 |
+--------------+
You are right. 你是对的。 Your pointer pointing to
x
not y
. 您的指针指向
x
而不是y
。 After pointer pointing to x
*address_of_x
will assigned to y
. 在指向
x
指针之后, *address_of_x
将分配给y
。 So y
will get the value of 5. 因此
y
的值为5。
Try to print value of x
, It will changed to 9. Because *address_of_x
pointing to x
. 尝试打印
x
值,它将更改为9。因为*address_of_x
指向x
。
printf("value of x = %d\n", x); //output = 9
Statement 声明
int y = *address_of_x;
assigns value at address_of_x
to y
and then after 将
address_of_x
值分配给y
,然后在
*address_of_x = 9;
is modifying the variable to which address_of_x
points to (which is x
here), not y
. 正在修改
address_of_x
指向的变量(此处为x
),而不是y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.