0

Here is my simple demostration of Call by Reference to pointer in C++:

#include <iostream>
using namespace std;

void myMethod(int* &x) {
    int t = 4;
    int* pt = &t;
    cout << "Address of t: " << pt << endl;
    cout << "Value of t: " << *pt << endl;
    
    x = pt;
    cout << "Address of x: " << x << endl;
    cout << "Value of x: " << *x << endl;
}

int main() {
    int y = 5;
    int* py = &y;
    cout << "Address of y: " << py << endl;
    cout << "Value of y: " << *py << endl;
    
    myMethod(py);
    cout << "Address of y after method: " << py << endl;
    cout << "Value of y after method: " << *py;
    return 0;
}

Output:

Address of y: 0x7ced454457cc
Value of y: 5
Address of t: 0x7ced4544579c
Value of t: 4
Address of x: 0x7ced4544579c
Value of x: 4
Address of y after method: 0x7ced4544579c
Value of y after method: 31205 

I am passing the reference of the pointer to y as an argument to the method myMethod(). In the method, the passed reference is assigned a new pointer to t, which in turn reassigns the pointer to y i.e., py = pt. Hence, after the method, when the pointer to y is printed, it prints the correct pointer which is the pointer to t. So, if we now print the dereferenced value of pointer to y, it should print the value 4. However, it prints some random number.

Why the Value of y after method is some random number, and not equal to 4?

jackmiller
  • 33
  • 3
  • 1
    `int t = 4; int* pt = &t; x = pt;` makes it point to a local variable that goes out of scope when the function ends. – 001 Oct 28 '21 at 18:13
  • But the address is preserved. Isn't that enough to retain the variable? – jackmiller Oct 28 '21 at 18:20
  • 2
    No. The program is free to reuse that memory once the variable goes out of scope. Trying to read it is "Undefined Behavior". – 001 Oct 28 '21 at 18:23
  • Thanks, now it works. The solution is to make the local variable ```t``` a global variable. – jackmiller Oct 28 '21 at 18:29
  • You could also make it [`static`](https://stackoverflow.com/a/15235626/669576). – 001 Oct 28 '21 at 18:31

0 Answers0