I'm trying to change my pointer to point to the address of x. So that it would work like it would if that commented piece was used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int change(int *p, int a)
{
p = &a;
}
int main()
{
int x = 13;
int * t = nullptr;
change(t, x);
//t = &x;
cout << *t;
}
So this is the only way to do this? Can you explain why the double pointer is necessary?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
void change(int **p, int a)
{
*p = &a;
}
int main()
{
int x = 13;
int * t = nullptr;
change(&t, x);
//t = &x;
cout << *t;
}
You still need to change a so that it is passed by reference, but the idea here is that you want to avoid the creation of temporary variables. Passing a pointer to t lets you modify t directly (set what it points to, e.t.c.) and passing a by reference is the same idea.
Btw, this is the correct prototype void change(int** p, int& a)
int *p - or, as I prefer to write it, int* p - is a variable like any other. It's a variable whose type is "pointer to int". It has a value, and that value is a memory address.
If you pass that variable into a function, than it follows the same rules as any other variable - it is passed in by value. That means that, while the value of p might be changed inside the function, the value of t outside the function is not changed.
If you want to change the value of p in such a way that it changes the value of the variable in the calling code, you need to pass by reference - just like you would any other variable.
Basically, yes (although it's technically only once the function has finished, not just at the end). Unless the compiler does some weird optimisation, but don't rely on that.