Can two separate pointers reference the same address? If so, can I change the value at that address with either pointer?
So, I have this code fragment:
int * iPtr ;
int * jPtr ;
int i = 5, k = 7;
iPtr = &i;
jPtr = iPtr ;
I have just started learning about pointers, and need to get some doubts cleared.
- is jPtr now essentially also pointing at i?
- I know I can change the value of i by using *iPtr, but how can I change the value of the object being pointed to by jPtr?
- How will changing the object being pointed to by jPtr affect the value of the object poin开发者_开发百科ted to by iPtr, and i ?
1000 1001 1002 1004 --> address location ( note: just indicative)
----------------------------
| 5 | 7 | 1000 | 1000 |
| i | j | iPtr | jPtr |
-----------------------------
^^ | |
||________| |
|_________________|
iPtr=&i; --> iPtr points to i ==> address of i is stored in iPtr ==> *iPtr contents of i
jPtr=iPtr; ->jPtr points to i
- Yep
jPtr
is pointing to the same memory address asiPtr
at the end of the given fragment. So, you can changei
using*jPtr
or*iPtr
.- Since
jPtr
holds the memory address ofi
, if you change*jPtr
, you are changingi
and as a direct result, changing the value of*iPtr
.
1: Yes, this is called pointer aliasing.
2: In the same way as you changed the value by using *iPtr, you can change the value of i by using *jPtr.
3: Since the pointers are aliased, meaning pointing to the same object, changing the value of the object that iPtr points to, also changes the value of the object that jPtr points to, because they're pointing to the same object.
- jPtr has the same assignment as iPtr, so it isn't essentially pointing at i - it is.
- The same way. *jPtr = x.
- They are the same object. Pointers work by address, which means if you assign one pointer to an object and another to that pointer, they are both aimed at the same object.
At least, that's how I recall it. I'm just getting back into this stuff.
- Yes
- The same: *jptr=value;
- If you change what jPtr points at (change the address it holds), it will not affect what iPtr points to. But as long as they point to the same thing, then changing the value (*jPtr=5) means the object pointed to by iPtr will also change
- Yes
*jptr=42
- Yes, it is the very same integer variable.
Question 1
Yes.
Question 2
*jPtr = ...
Question 3
It won't.
精彩评论