Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...