如何在C++中通过引用发送指向函数的指针

How send pointer to function by reference in C++?

本文关键字:函数 指针 引用 C++      更新时间:2023-10-16

如何通过引用将指针发送到函数?例如,我想把它发送到一个函数:

int **example;

谢谢。

只需这样声明:

void f(int*&);

当您将int x传递给函数foo()并收到类似的消息时

foo(int& var), here `int&` for `reference to int`, just replace it with whatever reference you want to pass, in your case `foo(int** &)` .
   ^^^^

如果您想通过引用传递char pointer(char*),只需执行foo(char* &)即可。

我的建议不仅针对这种情况,而且针对一般情况:当您对复杂类型有问题时,请使用typedef。它不仅可以帮助你解决这个特殊的问题,还可以了解它是如何更好地工作的:

class Foobar;
typedef Foobar* FoobarPtr;
void function( FoobarPtr &ref );

你的问题让很多人感到困惑,因为"send(pointer to function)"不同于"(send pointer)to(function)"。。。给定你的示例变量,我假设你想要后者。。。

参考方面表示在最后:

return_type function_name(int**& example)   // pass int** by ref

万一int*是您想要传递的,而示例代码中的**是通过引用传递的尝试——对于int*,它实际上应该是:

return_type function_name(int*& example)   // pass int* by ref

更新

您的代码:

void Input(float **&SparceMatrix1,int &Row1,int &Column1)
{
    cin>>Row1; cin>>Column1;
    *SparceMatrix1 = new float [Row1];
    /*for(int i=0;i<Row1;i++) (*SparceMatrix1)[i]=new float [Column1];*/
}

SparceMatrix1的类型(拼写为"稀疏"btw)意味着它可以跟踪这样的数据:

float** ---------> float* -----------> float
SparceMatrix1      *SparceMatrix1      **SparceMatrix1

因此,您尝试将*SparceMatrix1设置为指向Row1 float s,但SparceMatrix1还没有指向任何东西,因此您根本无法尊重/遵循它。相反,你应该这样做:

    if (cin >> Row1 >> Column1)
    {
        SparceMatrix1 = new float*[Row1];
        for (int i = 0; i < Row1; ++i)
            SparceMatrix1[i] = new float[Column1];
    }
    else
        SparceMatrix1 = nullptr;  // pre-C++11, use NULL, or throw...

正如你所看到的,正确地完成所有这些事情有点棘手,所以你最好使用std::vector<std::vector<float>>(这更容易纠正,但已经足够棘手了——你会发现太多关于它们的堆叠式问题)。