C++中如何通过引用发送指针函数?
如何通过引用将指针发送到函数? 例如,我想将其发送到一个函数:C++中如何通过引用发送指针函数?,c++,C++,如何通过引用将指针发送到函数? 例如,我想将其发送到一个函数: int **example; 谢谢。您的问题让很多人困惑,因为函数的发送指针不同于函数的发送指针。。。给出你的示例变量,我假设你想要后者 最后表示参考方面: return_type function_name(int**& example) // pass int** by ref 以防万一,int*是您想要传递的,而示例代码中的**部分是试图通过引用传递它-对于int*,它实际上应该是: return_type f
int **example;
谢谢。您的问题让很多人困惑,因为函数的发送指针不同于函数的发送指针。。。给出你的示例变量,我假设你想要后者 最后表示参考方面:
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设置为指向第1行浮动,但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,它更容易正确,但已经足够棘手-您也会发现太多关于它们的stackoverflow问题。只需声明如下:
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 pointerchar*,只需执行foochar*&。我的建议不仅适用于这种情况,而且适用于一般情况:当您遇到复杂类型的问题时,请使用typedef。它不仅有助于您解决这一问题,而且有助于您更好地理解它的工作原理:
class Foobar;
typedef Foobar* FoobarPtr;
void function( FoobarPtr &ref );
无效输入浮点**&SparceMatrix1,int&Row1,int&Column1{cin>>Row1;cin>>Column1;*SparceMatrix1=新浮点[Row1];/*forint i=0;i的可能重复项
class Foobar;
typedef Foobar* FoobarPtr;
void function( FoobarPtr &ref );