How to return matrix (2D array) from function? (C)
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 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)
.
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 < 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);
}