Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

c - Pointer to pointer clarification

I was following this tutorial about how does a pointer to a pointer work.

Let me quote the relevant passage:


    int i = 5, j = 6, k = 7;
    int *ip1 = &i, *ip2 = &j;

Now we can set

    int **ipp = &ip1;

and ipp points to ip1 which points to i. *ipp is ip1, and **ipp is i, or 5. We can illustrate the situation, with our familiar box-and-arrow notation, like this:

enter image description here

If then we say

    *ipp = ip2;

we've changed the pointer pointed to by ipp (that is, ip1) to contain a copy of ip2, so that it (ip1) now points at j:

enter image description here


My question is: Why in the second picture, is ipp still pointing to ip1 but not ip2?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Forget for a second about the pointing analogy. What a pointer really contains is a memory address. The & is the "address of" operator - i.e. it returns the address in memory of an object. The * operator gives you the object a pointer refers to, i.e. given a pointer containing an address, it returns the object at that memory address. So when you do *ipp = ip2, what you are doing is *ipp get the object at the address held in ipp which is ip1 and then assign to ip1 the value stored in ip2, which is the address of j.

Simply
& --> Address of
* --> Value at


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...