Passing a pointer as a function argument

61 Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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;
}
0
On
#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.