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.

Recommended Answers

All 4 Replies

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!

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!

Macobex,

If you're looking for more info on passing by reference, check out the first few paragraphs on http://www.cplusplus.com/doc/tutorial/functions2/

It has a lot of good information.

-D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.