There's no usage context for my question. Just a "what if" scenario I came up with.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
using std::cout;
struct A {
staticvoid func(int *pout) {
staticint i = 0;
pout = &i; // Expecting pout to now point to i
cout << "Addr(static int): " << std::hex << &i << "\n";
cout << "Addr(pout): " << std::hex << pout << "\n";
}
};
int main() {
int *pi = nullptr; // Want "pi" to point to A::func's static int. So it's accessible from main()
A::func(pi);
cout << "Outside pi's addr: " << std::hex << pi << "\n";
return 0;
}
You are passing the nullptr pointer into function A::func(), but overwriting that pointer inside function A::func() does not change the content of pointer variable "pi" inside your "main" function at all!
If you want that, you need to pass a pointer to the pointer variable, and dereference it inside A::func().
Try this:
1 2 3 4 5 6 7 8 9
staticvoid func(int **pout) {
staticint i = 0;
*pout = &i;
}
int main() {
int *pi = nullptr;
A::func(&pi);
}
Either that, or just:
1 2 3 4 5 6 7 8
staticint *func(void) {
staticint i = 0;
return &i;
}
int main() {
int *pi = A::func();
}
Mmm I see ... the address stored by pi (nullptr) was passed to func() by value. What I should have done was pass the address of the int pointer (int **) as you've suggested, to be initialized.