Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...