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?
coutit, so that is not good. Generally don't make parameters or return values point to local objects whose lifetime is restricted to the local scope.fooandblahon the heap usingnew, I still have the same problem. Should I edit my question to include that?newanddeleteshould generally be avoided in modern C++, but yes, that would be a good thing to include. I'm posting an answer soon.feellike pass-by-reference but the pointers are not. Pointers are an integral type. Meaning that it is just an integer holding the address. When you call the method, a copy of that integer (the pointer) is passed to the function. In C and also in C++ arrays are always passed as pointers.currArrays pointer to the function, when you do thisvoid poo(int *currArray)(Remember, pass by value). In order to do any thing change inside thecurrArray, you need either a referencevoid poo(int* &currArray)or the address of the pointervoid poo(int** currArray).