简体   繁体   English

将指针作为 function 参数传递

[英]Passing a pointer as a function argument

I am passing a pointer to a function with intent of modifying the data kept at the original address.我正在传递一个指向 function 的指针,目的是修改保存在原始地址的数据。

#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;
 }

I am able to get the desired output using this code, ie 5 7 7我可以使用此代码获得所需的 output,即 5 7 7

Just wanted to know if there is a better/easy to read way of handling this.只是想知道是否有更好/易于阅读的方法来处理这个问题。

You can make it pass-by-reference, if you just want to perform modification on the argument through the parameter in the function.如果您只想通过 function 中的参数对参数进行修改,则可以使其通过引用。

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

If you only have the pointer, you can still get the pointed object via operator* as @cdhowie suggested .如果您只有指针,您仍然可以按照@cdhowie 的建议通过operator*获得指向的 object。

Or pass-by-pointer is sufficient, then you don't need the intermediate pointer object x for passing to the function.或者按指针传递就足够了,那么您不需要中间指针 object x来传递给 function。 ie don't need to use pointer to pointer as your code showed.即不需要像您的代码显示的那样使用指向指针的指针。

void square(int* x)
{
    *x = *x + 2;
    cout<<*x<<" ";
}
int main()
{
    int y = 5;
    cout<<y<<" ";
    square(&y);
    cout<<y<<" ";
    return 0;
}
#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;
}

You don't need double indirection as per the sample code you've provided.根据您提供的示例代码,您不需要双重间接。 Just pass by a pointer instead of pointer to a pointer .只需通过指针而不是指向指针的指针 OR, use pass by reference.或者,使用通过引用传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM