我尝试返回 soduko 游戏的短[9][9] static Short[9][9] getRandomBoard();
static short[9][9] getRandomBoard()
{
short board[9][9];
bla bla bla.....................
bla bla bla.....................
bla bla bla.....................
return board;
}
我收到一个错误: 错误预期为“;”
最佳答案
问题 1
首先,您的函数声明需要更改。
static short[9][9] getRandomBoard()
应该是
static short** getRandomBoard()
问题2
getRandomBoard
的堆栈级别拥有名为 board
的变量。当函数的堆栈级别消失时,变量 board
的二维数组也会消失。这意味着您将返回一个指向不再有效的内存位置的指针。
记住这一点并避免将来出现问题的简单方法是,如果您使用new
,则会在 heap 上创建数据。 ;否则,它会在 stack 上创建.
使您的示例正常工作的最低限度的更改将给您带来以下结果:
static short** getRandomBoard() {
//Allocate 2D array on the heap, not on the stack
short** board = new short*[9];
//Create 2nd level of 2D array with arrays allocated on the heap
for(int i = 0; i < 9; i++) {
board[i] = new short[9];
}
//Populate 2D array here
return board;
}
话虽这么说,让函数分配内存并返回指向已分配内存的指针是不好的做法(如果可以避免的话)。这往往会导致 memory leaks 。相反,您应该让您的函数将数组作为参数。
static void populateRandomBoard(short board[9][9]) {
//Populate board here
}
然后使用这样的函数:
static int main() {
short board[9][9];
populateRandomBoard(board);
}
关于c++ - 静态短[9][9] getRandomBoard();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490552/