C++ error: “taking address of temporary array”

后端 未结 6 1910
渐次进展
渐次进展 2021-01-01 04:42

I am trying to declare an array inside an if-statement. I wrote my code this way so that the object stays in scope once the if-block exits, but now I have a new issue: \"tak

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 05:28

    You can use a temporary array to achieve this

    int temp [] = {0,1,0,1,-4,1,0,1,0};
    size_t n = sizeof(temp)/sizeof(int);
    
    if (condition == true )
    {
       maskArray = new int[n]{0,1,0,1,-4,1,0,1,0};
    }
    
    // ...
    
    delete [] maskArray; // Free memory after use
    

    Or simply use a std::vector

    std::vector maskArray;
    
    if( condition == true )
    {
      maskArray = {0,1,0,1,-4,1,0,1,0}; // C++11 initializer_list vector assignment
    }
    

提交回复
热议问题