c++pointerspass-by-referencepass-by-pointer

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.

#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, i.e 5 7 7

Just wanted to know if there is a better/easy to read way of handling this.


Solution

  • You can make it pass-by-reference, if you just want to perform modification on the argument through the parameter in the 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.

    Or pass-by-pointer is sufficient, then you don't need the intermediate pointer object x for passing to the function. i.e. 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;
    }