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? 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. You assign it the same value as x
(through a pointer), but x
and y
are different variables.
At this point, assigning to *address_of_x
will change the value of x
, but not y
.
y
isn't a pointer, it is an integer. This line:
int y = *address_of_x;
basically says "take the value pointed to by address_of_x
and copy it into y
.
If you had instead done this:
int *y = address_of_x;
Then *y
would be 9
.
Yes that was because of the ordering of the commands when int y = *address_of_x;
this executed the 'address_of_x' contained 5
and hence y
got that value
+--------------+
| 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
. After pointer pointing to x
*address_of_x
will assigned to y
. So y
will get the value of 5.
Try to print value of x
, It will changed to 9. Because *address_of_x
pointing to 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 = 9;
is modifying the variable to which address_of_x
points to (which is x
here), not y
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.