First off, I apologize if this has been asked before. I can’t seem to find the right info.
The following code does not print “300” as I thought it would:
#include <iostream>
int main()
{
int *array;
int *arrayCopy = array;
array = new int[4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
std::cout << arrayCopy[2];
return 0;
}
However, it does, if I move the line
int *arrayCopy = array;
below the line that follows it in the above code. Why is that?
(PS: I know there is a memory leak, and that std::vector is better… I’m just curious).
Maybe you’re thinking of using a reference to a pointer? Here’s what happens with your current code:
If you did something like this though, it’s different:
Technically, this isn’t entirely true because different things are happening. A reference is essentially the same level of indirection as a pointer, except the compiler does all the dereferencing for you. But what I described is essentially how it works. If you just stick the extra
&in there, your code will do what you were thinking.