代码之家  ›  专栏  ›  技术社区  ›  mustafabar

在C++中,使用函数无效FO(int *p)有什么用?

  •  0
  • mustafabar  · 技术社区  · 17 年前

    我的同事告诉我 void foo(int** p) 在C中用作out参数。有人能准确地解释怎么做吗?

    我知道这个主意,但有些东西不见了。我知道如果我们通过指针 p 本身到 foo(*p) 功能体是这样的 p = new int() ,我们可能有一个悬空的修改器!但如何 foo(**p) 防止类似的事情发生?

    5 回复  |  直到 9 年前
        1
  •  10
  •   aJ.    17 年前
    void foo(int** p)
    {
     *p = new int;
    }
    
    
    void main()
    {
     int *p = NULL;
    
    foo(&p);
    //unless you pass the pointer to p, the memory allocated in the 
    //function foo is not available here.
    
    foo(p); // lets assume foo is foo(int* p)
    
    //when you pass only pointer p to `foo()` then the value of the pointer will be 
    //passed ( pass by value) to foo() and hence, any modification to pointer p ( in
    // the form of allocating memory also) will not be available after the
    // control returns from foo()
    // The p will still points to NULL here, not the memory allocated in foo().  
    
    }
    
        2
  •  3
  •   Daniel Daranas    17 年前

    int **p 是 不 二维数组。这是一个 指向指向整数的指针 .

        3
  •  3
  •   Adisak    17 年前

    其他人解释了什么 void foo(int **p) 但他们没有回答你问题的另一部分:“当参数不是二维数组时”。

    这里的答案是参数 int**p 是 从未 二维数组。即使将其取消引用为p[行][列],也有一些主要区别:

    1)内存不是二维数组,而是指向“row”指针的一维数组的指针,每个指针指向一个单独的一维整数数组(此处以“column”索引)。

    2)“行”不必是连续的(即不能添加行宽以获取下一行)。

    3)“行”不必具有相同的大小(它们可能因可访问元素的数量而异)。

    要将二维数组传递给函数,可以使用各种函数签名。最容易的是 void foo(int p[25][15]) (其中25和15是数组的行和列大小)。

    以下二维数组的函数签名在调用时也会生成相同的代码: void foo(int (&p)[25][15]) 和 void foo(int (*p)[25][15]) 和 void foo(int p[][15]) . 这里是最后一个版本 p[][15] 允许您处理具有固定列宽但行数不同的二维数组。

    冒着过于“聪明”的风险,您可以将二维数组作为 void foo2(int *p) 如果传递第一个元素的地址(或者可以使用 int a[25][15]; foo2(a[0]); )但是,在foo2中,必须使用指针数学来访问二维数组的行和列,并且还必须更改调用函数的方式(传递int*而不是数组指针)。这种“聪明”的技术有时在C中很有用,当你必须处理不同尺寸的二维数组时。在C++中,只使用数组大小的模板作为模板参数来处理各种大小的2D数组更容易。

        4
  •  1
  •   xtofl Adam Rosenfield    17 年前

    指向指针的指针…有点模糊:通过引用传递指针。使用typedef可以大大简化以下操作:

    typedef int* SomeType;
    
    // C-style output parameter: pass address of variable
    void create( SomeType* aVariable ) {
       *aVariable = new int;
    }
    
    // easier, more idiomatic C++: pass variable by reference
    void create2( SomeType& aVariable ) {
       aVariable = new int;
    }
    
    int main() {
       SomeType localVar;
       create( &localVar );
       create2( localVar );
    }
    
        5
  •  0
  •   Gabb0    17 年前

    使用一个**p,你可以改变在程序的另一部分中*p所指的内容,并且函数仍然在正确的p上工作。