This has been bothering me for over a week now. It's possible I missed the post that explains this, but I have read a bunch of posts/articles and they either don't tell me anything I don't know or are over my head.
Consider this:
#include<iostream>
using namespace std;
void poo(int *currArray){
cout << "*currArray: " << currArray << endl;
int * blah = new int [5];
cout << "blah: " << blah << endl;
currArray = blah;
cout << "currArray after switch " << currArray << endl;
}
int main(){
int * foo = new int [5];
cout << "foo: " << foo << endl;
poo(foo);
cout << "foo after poo " << foo << endl;
}
which yields the output:
foo: 0x7ffdd5818f20
*currArray: 0x7ffdd5818f20
blah: 0x7ffdd5818ef0
currArray after switch 0x7ffdd5818ef0
foo after poo 0x7ffdd5818f20
As you can see, while the address switching happens inside the function, it doesn't carry over to the main function. I'm also aware this is leaking memory, but I don't think it's relevant to the question.
My understanding is that arrays essentially point to the address of its first element. It is also my understanding that arrays are passed 'by reference'. I.e., the address of the array is passed.
So why is it that the address switching does not persist after poo
? Have I not changed the pointer of currArray
, which is an alias for foo
, to be the pointer for blah
?