return pointer to data declared in function

前端 未结 11 1617
南旧
南旧 2020-12-17 21:11

I know this won\'T work because the variable x gets destroyed when the function returns:

int* myFunction()
{
    int x = 4; return &x;
}
<
11条回答
  •  半阙折子戏
    2020-12-17 21:33

    There is another approach - declare x static. In this case it will be located in data segment, not on stack, therefore it is available (and persistent) during the program runtime.

    int *myFunction(void)
    {
        static int x = 4;
        return &x;
    }
    

    Please note that assignment x=4 will be performed only on first call of myFunction:

    int *foo = myFunction();   // foo is 4
    *foo = 10;                 // foo is 10
    *foo = myFunction();       // foo is 10
    

    NB! Using function-scope static variables isn't tread-safe technique.

提交回复
热议问题