C++ - explain about pointers


I expected the address of the ref should be 1.
Because I assigned 1 (*ptr) to the address of ref (&ref). (not value of ref)
But the value of ref is 1 and the address of ref is like 0x0058e8a8

	int* ptr = new int(1);
	int& ref = *ptr;
	cout << ref << '\n';
	ptr = new int(2);
	cout << ref << '\n';
	delete& ref;
	delete ptr;
&ref is not address of ref. It is of type reference to int. Using ref is the same as using *ptr.

as noted, you have confused address of and reference syntax. Unfortunately references are a lot like pointers, and unfortunately, they use the same & symbol. They are best though of at first as totally different things, until you get it down solidly.

but on top of that, to clarify,
the address of ref will be equal to ptr on line 3 you didn't print the address of ref, but that does not change this important fact.

somewhere, out in ram (your hex value) is a block of bytes (size of int) with a value of 1: you made this on line 1. If you think of ram as a giant array of bytes, this is the index into it.
ptr contains the index into ram.
ref is the integer. all you did here is rename the integer out in ram to 'ref'. ref IS an integer!
you printed ref. it is an integer valued at 1. the cout prints 1.
ptr gets moved to a new index in ram that holds a new block of bytes that mean 2
ref has not changed. ref is still just a name applied to the original block of memory.
deleting the address of ref on line 6 releases the original memory. This is critical: &ref is a pointer: it is the original line 1 ptr index into ram.
deleting ptr release the second block of memory.

as a general rule of thumb to get started:
when you see a variable being created/defined with & in it, that is a reference, and it renames something. both names are the same entity now, and changing one changes the other.
int & i = x; //change x, you change i. change i, you change x. 2 names, 1 thing.
void foo(int &i); //a function. change i, and what was passed to the function will be modifed!

when you see a variable with & on it but it is not being created, that is a pointer.
char *c = &mystring[3];

and again, critical:
I said that changing x changes i above.
so why, when you change ptr, does ref not change in your code?
because: ref is not ptr.
ref is the thing ptr points to, not ptr.
this will make it a little easier to see:
int x = 1;
int* ptr = &x; //ptr is a pointer to the index in ram where the bytes that make up x are stored.
int &ref = *ptr; //now it is easier to say: ref IS x
Topic archived. No new replies allowed.