Passing a 2D array to a function in C
- by Tyler Treat
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.