How to return the address of a function's static variable?

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 {
   static void func(int *pout) {
      static int 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; 
}


Output:

Addr(static int): 0x600ed4
Addr(pout): 0x600ed4
Outside pi's addr: 0


I expected func() to initialize pi to point to static int inside func() but it still points to nullptr. How come?
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
static void func(int **pout) {
    static int i = 0; 
    *pout = &i;
}

int main() {
    int *pi = nullptr;
    A::func(&pi); 
}


Either that, or just:
1
2
3
4
5
6
7
8
static int *func(void) {
    static int i = 0; 
    return &i;
}

int main() {
    int *pi = A::func();
}
Last edited on
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.

Thanks kigar64551.
Could also pass as int*& - ref to int* - which would avoid having to de-ref in the body.
Topic archived. No new replies allowed.