且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何返回二维字符数组 C++?

更新时间:2022-06-27 02:48:22

是的,看看你在做什么,返回一个指向在堆栈上创建的对象(名为 board 的数组)的指针.数组在超出范围时被销毁,因此指针不再指向任何有效对象(悬空指针).

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).

您需要使用 new 来确保在堆上分配数组.在现代 C++ 中创建动态分配数组的神圣方法是使用类似 std::vector 类的东西,尽管这里更复杂,因为您正在尝试创建一个二维数组.

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;
}