开发者

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.

  1. is jPtr now essentially also pointing at i?
  2. 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?
  3. 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 


  1. Yep
  2. jPtr is pointing to the same memory address as iPtr at the end of the given fragment. So, you can change i using *jPtr or *iPtr.
  3. Since jPtr holds the memory address of i, if you change *jPtr, you are changing i 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.


  1. jPtr has the same assignment as iPtr, so it isn't essentially pointing at i - it is.
  2. The same way. *jPtr = x.
  3. 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.


  1. Yes
  2. The same: *jptr=value;
  3. 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


  1. Yes
  2. *jptr=42
  3. Yes, it is the very same integer variable.


Question 1

Yes.

Question 2

*jPtr = ...

Question 3

It won't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜