Question about using pointer with reference

Hi everyone!

I have problems in using pointer with reference. So, I make simple program to clarify them.

First of all, this is my code and its output. Please notice line (*) and (**):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void RefFunc(int*& a){
	int q = 888;
	a = &q;  //PROPLEM HERE (*) - //*a = q
	cout << "address of a after assign= " << &a << endl;
	cout << "value of a after assign= " << *a << endl;
}

int main ()
{
	int * ptr;
	int p = 777;
	ptr = &p;	
	RefFunc((int*&)ptr); //PROPLEM HERE(**) - ptr
	cout << "address of ptr after RefFunc function = " << &ptr << endl;
	cout << "value of ptr after RefFunc function = " << *ptr << endl;
	getch();
	return 0;
}



        address of a after assign = 0012FF28
        value of a after assign = 888
        address of ptr after RefFunc function = 0012FF28
        value of ptr after RefFunc function = 1730693832


These are what I tried:
1- I think "value of ptr after RefFunc function" should be the same with the value of variable 'a' in RefFunc because I use pointer - reference (*&) in RefFunc function. But it is not...(see the output)

2- When I modified line (*) to "*a = q": this time, "value of ptr after RefFunc function" is the same with 'a' in RefFunc (888).

3- In line (**) - I used RefFunc((int*&)ptr) or RefFunc(ptr): these two ways have the same results to output.

Anyone can explain for me the difference between:
1- <a = &q> and <*a = q> in line (*) in this situation, why *ptr does not change its value when I use <a = &q> whereas it does when I used <*a = q>?

2- <RefFunc((int*&)ptr)> and <RefFunc(ptr)>: what does it means in this case?


Thanks everyone in advance!!







Last edited on
You are returning the address of a temporary. The variable no longer exists in main().
Thanks PanGalactic,

I tried to declare q as global variable and it does well.

How about <RefFunc((int*&)ptr)> and <RefFunc(ptr)> ?



I have no idea what it means to cast a variable to a reference. It doesn't make much sense to me.
Topic archived. No new replies allowed.