So, I'm really frustrated with this problem. I desperately need some good explanation about this. Why does the calling function does not reflect the change done in the called function? despite the fact that I pass the variable via pointer. Any explanations please. Thanks in advance.

#include <iostream>
using namespace std;

void foo(int *x) {
	int *y = new int(999);
	x = y;
}

int main(void) {	
	int *x = new int(1);
	foo(x);

	cout << *x << endl;
	cin.get();
	return 0;
}

In main: x = 1;
In foo: x = 999;
In main: x = 1;

Why ?
and How will I reflect the change on the calling function (without using RETURN) ?
THANKS.

I'm still pretty new at C++, but try passing your argument by reference instead of pointer:

void foo(int &x) {
	int y = new int(999);
	x = y;
}

Passing arguments by reference should allow the function to directly manipulate that variable without the need for a return statement. I hope that helps.

-D

Why does the calling function does not reflect the change done in the called function? despite the fact that I pass the variable via pointer.

Passing by pointer only means that the pointed to object can be changed. If you want to repoint the pointer to another address, it has to be passed by pointer too because pointers are also passed by value:

#include <iostream>
using namespace std;

void foonochange(int *x) {
	int *y = new int(999);
	x = y;
}

void foochange(int **x) {
	int *y = new int(999);
	*x = y;
}

int main(void) {	
	int *x = new int(1);

	foonochange(x);
	cout << *x << endl;

	foochange(&x);
	cout << *x << endl;

	cin.get();
	return 0;
}

But this is C++, and C++ has pass by reference. You can pass a reference to the pointer and not worry about adding another explicit level of indirection:

#include <iostream>
using namespace std;

void foonochange(int *x) {
	int *y = new int(999);
	x = y;
}

void foochange(int*& x) {
	int *y = new int(999);
	x = y;
}

int main(void) {	
	int *x = new int(1);

	foonochange(x);
	cout << *x << endl;

	foochange(x);
	cout << *x << endl;

	cin.get();
	return 0;
}

@Tom Gunn

Thanks. That one works. But still the concept is a little bit confusing for me. I'll try to understand it. Thanks for the help!

This question has already been answered. Start a new discussion instead.