how to return two dimensional char array c++?

前端 未结 8 2105
攒了一身酷
攒了一身酷 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:42

    Don't return pointer to a local variable, as other mentioned. If I were forced to do what you want to achieve, first I'd go for std::vector. Since you haven't learnt std::vector, here is another way:

    void createBoard(char board[16][10])
    {  
      int j =0;int i = 0;
      for(i=0; i<16;i++){
            for( j=0;j<10;j++){   
                    board[i][j]=(char)201;
            }       
      }
    }
    
    0 讨论(0)
  • 2020-12-03 15:43

    You must not return a pointer to a functions local variables because this space gets overwritten as soon as the function returns.

    The storage associated with board is on the function's stack.

    0 讨论(0)
  • 2020-12-03 15:45

    The simple answer to your question is char**.

    Having said that, DON'T DO IT ! Your "board" variable won't last outside createBoard().

    Use boost::multi_array and pass it as a reference to createBoard() or return it directly (but if you do that, it will be copied).

    0 讨论(0)
  • 2020-12-03 15:46

    The best approach is create a board class and make the ctreateBoard function its constructor:

    class Board {
      private:
       char mSquares[16][10];
    
       public:
        Board() {
            for(int i=0; i<16;i++){
            for( int j=0;j<10;j++){   
                    mSquares[i][j]=201;
            }       
        }
    
       // suitable member functions here
     };
    

    For information on how to use such a class, there is no substitute for reading a good book. I strongly recommend Accelerated C++ by Andrew Koenig and Barbra Moo.

    0 讨论(0)
  • 2020-12-03 15:46

    You should return char** instead of char*

    0 讨论(0)
  • 2020-12-03 15:59

    Yeah see what you are doing there is returning a pointer to a object (the array called board) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).

    You need to make sure that the array is allocated on the heap instead, using new. The sanctified method to create a dynamically allocated array in modern C++ is to use something like the std::vector class, although that's more complicated here since you are trying to create a 2D array.

    char **createBoard()
    {
        char **board=new char*[16];
        for (int i=0; i<16; i++)
        {
           board[i] = new char[10];
           for (int j=0; j<10; j++)
             board[i][j]=(char)201;
        }
    
        return board;
    }
    
    void freeBoard(char **board)
    {
        for (int i=0; i<16; i++)
          delete [] board[i];
        delete [] board;
    }
    
    0 讨论(0)
提交回复
热议问题