改变指针的函数,C [英] changing pointers in functions, c

查看:94
本文介绍了改变指针的函数,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?

推荐答案

您是对在第一位,但如果你已经分配的结构,那么你可以传递一个指针。但是,如果函数分配的结构,那么无论你用函数返回收集新分配结构的价值或你在一个指针传递给在参数列表中的指针。

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.

(我没有得到一个C编译器来的手,但我试图写一些例子)。

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


  • 您已经分配的指针



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

    void intix(struct x* px){
        px-> ....
    }
 


  • 的函数分配的指针

  • 
    
         int main() {
           struct x *px = initx(); 
         }
    
         struct x* intix(){
            struct x *px = malloc(...);
            px-> ....
            return px;
         }
     


    • 的函数分配的指针

    • 
      
           int main() {
             struct x *px;
             initx(&px); 
           }
      
           void intix(struct x** ppx){
              struct x *px = malloc(...);
              px-> ....
              *ppx = px;
           }
       

      这篇关于改变指针的函数,C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆