how to return two dimensional char array c++?

前端 未结 8 2108
攒了一身酷
攒了一身酷 2020-12-03 15:23

i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..

char *createBoard( ){  
  char          


        
相关标签:
8条回答
  • 2020-12-03 15:59

    This approach will not work. If you return a pointer to a local variable you'll run into undefined behaviour. Instead allocate an array on heap with new and copy data into it manually indexing it.

    0 讨论(0)
  • 2020-12-03 16:08

    I would really recommend using STL vector<> or boost/multi_array containers for this.

    If you must use arrays, then I would recommend using a typedef to define the array.

    typedef char[16][10] TBoard;
    

    You could also return

     char**
    

    ...but then you would need to typecast it to the correct size in order to index it correctly. C++ does not support dynamic multiple dimension arrays.

    Also as others have suggested you can't return an object on the stack (i.e., local variable)

    0 讨论(0)
提交回复
热议问题