How to return matrix (2D array) from function? (C)

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!