return pointer to data declared in function

前端 未结 11 1622
南旧
南旧 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 21:35

    I would try something like this:

    int myFunction2b( int * px )
    {
      if( px )
      {
        *px = 4;
        return 1;
      }
    
      // Choice 1: Assert or Report Error
      // Choice 2: Allocate memory for x. Caller has to be written accordingly.
    
      // My choice is 1
      assert( 0 && "Argument is NULL pointer" );
      return 0;
    
    }
    

提交回复
热议问题