Passing a 2D array to a function in C

Posted by Tyler Treat on Stack Overflow See other posts from Stack Overflow or by Tyler Treat
Published on 2011-02-12T23:12:48Z Indexed on 2011/02/12 23:25 UTC
Read the original article Hit count: 237

Filed under:
|
|
|

I have, essentially, a matrix of data (lets say ints) that I would like to store in a 2D array in which the dimensions are not known until runtime (say x columns and y rows). I want to populate the array in a function, so I assume I need to do something like this:

int main(int argc, char **argv) {
    int y = atoi(argv[1]);
    int x = atoi(argv[2]);
    int **matrix = malloc(x * sizeof(int*));
    populateMatrix(matrix, y, x);
    return 0;
}

void populateMatrix(**matrix, int y, int x) {
    int i, j;
    for (i = 0; i < y; i++) {
        for (j = 0; j < x; j++) {
            matrix[i][j] = i * j; // populated with trivial data to keep it simple
        }
    }
}

Obviously this doesn't work, but I'm not sure how to do what I'm describing exactly.

© Stack Overflow or respective owner

Related posts about c

    Related posts about arrays