【问题标题】:Passing a pointer as a function argument将指针作为函数参数传递
【发布时间】:2020-11-08 03:06:38
【问题描述】:

我正在传递一个指向函数的指针,目的是修改保存在原始地址的数据。

#include<bits/stdc++.h>
using namespace std;
void square(int **x)
{
    **x = **x + 2;
    cout<<**x<<" ";
}
int main()
{
    int y = 5;
    int *x = &y;
    cout<<*x<<" ";
    square(&x);
    cout<<*x<<" ";
    return 0;
 }

我能够使用此代码获得所需的输出,即 5 7 7

只是想知道是否有更好/易于阅读的方法来处理这个问题。

【问题讨论】:

  • #include&lt;bits/stdc++.h&gt; 和 using namespace std; 都是不好的做法。不要使用它们。
  • 您是否有理由要使用int **x 而不是只写square(x) 或square(&amp;y) 并将函数更改为void square(int *x) { *x = *x + 2; cout&lt;&lt;*x&lt;&lt;" "; } ?
  • @cdhowie,在实际代码中没有使用它们,这只是一个临时的sn-p来解释我的问题。
  • @t.niese,这就是我想要的,非常感谢。您能否解释一下这两种方法之间的区别,因为它们似乎给出了相同的结果。

标签: c++ pointers pass-by-reference pass-by-pointer


【解决方案1】:

如果你只是想通过函数中的参数对参数进行修改,你可以让它通过引用。

void square(int& x)
{
    x = x + 2;
    cout<<x<<" ";
}
int main()
{
    int y = 5;
    cout<<y<<" ";
    square(y);
    cout<<y<<" ";
    return 0;
}

如果你只有指针,你仍然可以通过operator*作为@cdhowie suggested获取指向的对象。

或者按指针传递就足够了,那么你不需要中间指针对象x 来传递给函数。即不需要像您的代码显示的那样使用指向指针的指针。

void square(int* x)
{
    *x = *x + 2;
    cout<<*x<<" ";
}
int main()
{
    int y = 5;
    cout<<y<<" ";
    square(&y);
    cout<<y<<" ";
    return 0;
}

【讨论】:

  • 感谢您的回答,但问题是我想将指针传递给该函数(因为在我想使用它的实际代码中,我只有指向该变量的指针,而不是实际变量)
  • @ShubhamChhabra 您仍然可以通过引用传递指向的值;取消引用指针会导致左值引用。 int *p = &amp;y; square(*p);
【解决方案2】:
#include <iostream>
using namespace std;
void square(int *x)
{
    *x = *x + 2;
    cout << *x << " ";
}

int main()
{
    int y = 5;
    cout<< y <<" ";
    square(&y);
    cout<< y << " ";
    return 0;
}

根据您提供的示例代码,您不需要双重间接。只需传递一个指针而不是指向指针的指针。 或者,使用引用传递。

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 2013-03-16
    • 2015-01-29
    • 1970-01-01
    • 2019-08-17
    • 2012-11-28
    • 2012-01-24
    • 1970-01-01
    相关资源
    最近更新 更多