Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 without using structs \ dynamic allocations?

I'm using Microsoft Visual C++ Express 2010.

like image 617
Billie Avatar asked Dec 30 '12 06:12

Billie


People also ask

Can I return a 2D array from a function in C?

This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated. The source code of returning a two-dimensional array with reference to matrix addition is given here. #include <stdio.

Can a function return a matrix in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

How do you return a two-dimensional array?

Use Pointer to Pointer Notation to Return 2D Array From Function in C++ As an alternative, we can use a pointer to pointer notation to return the array from the function. This method has an advantage over others if the objects to be returned are allocated dynamically.

How do you print a 2D array in matrix form?

public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].


2 Answers

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);
 }
like image 167
Israel Unterman Avatar answered Oct 02 '22 11:10

Israel Unterman


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).

like image 45
WhozCraig Avatar answered Oct 02 '22 09:10

WhozCraig