1

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 4
    Both [`#include`](https://stackoverflow.com/q/31816095/501250) and [`using namespace std;`](https://stackoverflow.com/q/1452721/501250) are bad practice. Don't use them. – cdhowie Jul 18 '20 at 12:48
  • 2
    Is there a reason you want to use `int **x` instead of just writing `square(x)` or `square(&y)` and change the function to `void square(int *x) { *x = *x + 2; cout<<*x<<" "; }` ? – t.niese Jul 18 '20 at 12:49
  • @cdhowie, Not using them in the actual code, this is just a temporary snippet to explain my problem. – Shubham Chhabra Jul 18 '20 at 12:49
  • @t.niese, That is what I was looking for, Thank you so much. Could you please explain what is the difference between the two approaches as they seem to give the same result. – Shubham Chhabra Jul 18 '20 at 12:52

2 Answers2

3

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;
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thank you for your answer, but the thing is I want to pass pointer to that function ( because in the actual code I want to use this for, I only have the pointer to that variable, not the actual variable ) – Shubham Chhabra Jul 18 '20 at 12:48
  • 2
    @ShubhamChhabra You can still pass a pointed-to value by reference; dereferencing a pointer results in an lvalue reference. `int *p = &y; square(*p);` – cdhowie Jul 18 '20 at 12:49
1
#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.

aep
  • 1,583
  • 10
  • 18