C语言 如何从函数返回矩阵(二维数组)?(C)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14088804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return matrix (2D array) from function? (C)
提问by Billie
I created a function that generates a bingo board and I want to return the bingo board.
我创建了一个生成宾果板的函数,我想返回宾果板。
as I didn't expect for , it doesn't work.
正如我没想到的那样,它不起作用。
here is the function:
这是功能:
int** generateBoard() {
int board[N][M], i, j , fillNum;
Boolean exists = True;
// initilize seed
srand(time(NULL));
// fill up..
for(i = 0; i < N; ++i) {
for(j = 0; j < M; ++j) {
exists = True;
while(exists) {
fillNum = rand()%MAX_RANGE + 1; // limit up to MAX_RANGE
if(beenAdded(board, fillNum) == Exist) {
continue;
} else {
board[i][j] = fillNum;
exists = False;
}
}
}
}
return board;
}
I have a compilcation error (the red subline) at "return board" line.
我在“返回板”行有一个编译错误(红色子线)。
is there way to return a 2D array withoutusing structs \ dynamic allocations?
有没有办法在不使用结构\动态分配的情况下返回二维数组?
I'm using Microsoft Visual C++ Express 2010.
我正在使用 Microsoft Visual C++ Express 2010。
采纳答案by WhozCraig
Someone has to own the memory of that board somewhere, and more importantly, that ownership must extend back to the caller of this function. Without dynamic allocation, your only other real alternative is to send it into the function as in in/out parameter.
有人必须在某处拥有该板的内存,更重要的是,所有权必须扩展回该函数的调用者。如果没有动态分配,您唯一的其他真正选择是将其作为输入/输出参数发送到函数中。
void generateBoard(size_t N, size_t M, int board[N][M])
{
int i, j , fillNum;
Boolean exists = True;
// initilize seed
srand(time(NULL));
// fill up..
for(i = 0; i < N; ++i) {
for(j = 0; j < M; ++j) {
exists = True;
while(exists) {
fillNum = rand()%MAX_RANGE + 1; // limit up to MAX_RANGE
if(beenAdded(board, fillNum) == Exist) {
continue;
} else {
board[i][j] = fillNum;
exists = False;
}
}
}
}
}
and invoke like this from your caller:
并从您的来电者那里调用:
int main()
{
const size_t N = 10;
const size_t M = 10;
int board[N][M];
generateBoard(N,M,board);
...
}
I would also consider relocatting the srand()call to the startup code in main(). It should ideally never be in some potentially repeat-callable function, and should be guaranteed to only be executed onceper process execution. (note: I honestly can't remember if it is once per threadexecution, but at this point in your coding learning curve I'm guessing multi-threading is not on the radar yet).
我还会考虑将srand()调用重新定位到main(). 理想情况下,它应该永远不会出现在某些潜在的可重复调用的函数中,并且应该保证每个进程执行只执行一次。(注意:老实说,我不记得是不是每个线程执行一次,但是在您的编码学习曲线的这一点上,我猜测多线程还没有出现)。
Finally, your random-fill loop is needlessly repetitious. There are better alternatives generating what you're apparently trying to do: create a random permutation of an existing set of numbers. As written you could spin for some time trying to fill those last few slots, depending on how much larger MAX_RANGEis compared to (N*M).
最后,您的随机填充循环是不必要的重复。有更好的替代方案可以生成您显然想要做的事情:创建一组现有数字的随机排列。正如所写的那样,您可以旋转一段时间来尝试填充最后几个插槽,具体取决于MAX_RANGE与(N*M).
回答by Israel Unterman
You defined boardas a local variable - its memory is dealoccated as the function goes out of scope.
您定义board为局部变量 - 当函数超出范围时,它的内存被释放。
You can declare the board global, or you can create it dynamically like so:
您可以将板声明为全局,也可以像这样动态创建它:
int **allocate_board(int Rows, int Cols)
{
// allocate Rows rows, each row is a pointer to int
int **board = (int **)malloc(Rows * sizeof(int *));
int row;
// for each row allocate Cols ints
for (row = 0; row < Rows; row++) {
board[row] = (int *)malloc(Cols * sizeof(int));
}
return board;
}
You will need to dynamically free the board:
您将需要动态释放板:
// you must supply the number of rows
void free_board(int **board, int Rows)
{
int row;
// first free each row
for (row = 0; row < Rows; row++) {
free(board[row]);
}
// Eventually free the memory of the pointers to the rows
free(board);
}

