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
686 views
in Technique[技术] by (71.8m points)

changing pointers in functions, c

I'll say in advance that I'm asking about pointers to pointers, so my words may be a bit vague, but try to stay with me :)

I am trying to understand how changing a pointer passed as an argument takes effect outside the scope of the function. So far this is what I understand: if a pointer is passed as an argument to a function, I can only change what the pointer points to, and not the pointer itself (I'm talking about a change that will take effect outside the scope of the function, as I said). And if I want to change what the pointer is pointing to, I have to pass a pointer to a pointer.

Am I right so far? Also, I've noticed that when I have a struct that holds some pointers, if I want to initialize those pointers I have to pass the struct to the initialization function as a pointer to pointer. Is this for the same reason?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You are right in the first bit but if you've allocated the struct then you can pass a pointer to it. However, if the function allocated the struct, then either you use the function return to collect the value of the newly allocated struct or you pass in a pointer to a pointer in the parameter list.

(I've not got a c compiler to hand but I've tried to write some examples).

  • You've allocated the pointer

    int main() {
       struct x *px = malloc(...);
       initx(px); 
    }

    void intix(struct x* px){
        px-> ....
    }
 
  • The function allocated the pointer

     int main() {
       struct x *px = initx(); 
     }

     struct x* intix(){
        struct x *px = malloc(...);
        px-> ....
        return px;
     }
 
  • The function allocated the pointer

     int main() {
       struct x *px;
       initx(&px); 
     }

     void intix(struct x** ppx){
        struct x *px = malloc(...);
        px-> ....
        *ppx = px;
     }
 

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

...