可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
I have a compilcation error (the red subline) at "return board" line.
is there way to return a 2D array without using structs \ dynamic allocations?
I'm using Microsoft Visual C++ Express 2010.
回答1:
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
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 once per process execution. (note: I honestly can't remember if it is once per thread execution, but at this point in your coding learning curve I'm guessing multi-threading is not on the radar yet).
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_RANGE
is compared to (N*M)
.
回答2:
You defined board
as a local variable - its memory is dealoccated as the function goes out of scope.
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
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