Home » Miscellanea » Programming Languages » C/C++ » Passing 2D Arrays

# Passing 2D Arrays

Multi-dimensional arrays, and especially 2-dimensional arrays (i.e., matrices), come in handy very often when approaching several computational problems.
Unfortunately, the C programming language does not provide a built-in support to multi-dimensional arrays, in fact there are several ways to simulate them.
The way to pass such arrays to a function depends on how multiple dimensions are simulated. To this end, we here propose 3 different methods as follows.

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time.

```
#define N_ROWS 4
#define N_COLS 5

void initMatrix(int matrix[N_ROWS][N_COLS]) {
int i, j;

for (i=0; i<N_ROWS; i++) {
for (j=0; j<N_COLS; j++) {
matrix[i][j] = i*j;
}
}
}

int main() {

int matrix[N_ROWS][N_COLS];
initMatrix(matrix);

}

```

2) Use a dynamically-allocated array of pointers to dynamically-allocated arrays. This is used mostly when the array bounds are not known until runtime.

```
void initMatrix(int** matrix, int n_rows, int n_cols) {
int i, j;

for (i=0; i<n_rows; i++) {
for (j=0; j<n_cols; j++) {
matrix[i][j] = i*j;
}
}
}

int main() {

int n_rows, n_cols, i;
int **matrix;

/* obtain values for n_rows & n_cols */

/* dynamically allocate the matrix using malloc */
matrix = malloc(n_rows * sizeof *matrix);

for (i=0; i<n_rows; i++) {
matrix[i] = malloc(n_cols * sizeof *matrix[i]);
}

/* use the array */
initMatrix(matrix, n_rows, n_cols);

/* deallocate the matrix */
for (i=0; i<n_rows; i++) {
free(matrix[i]);
}
free(matrix);

}
```

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically-allocated (i.e., fixed-size) and dynamically-allocated arrays.

```
void initMatrix(int* matrix, int n_rows, int n_cols) {
int i, j;

for (i=0; i<n_rows; i++) {
for (j=0; j<n_cols; j++) {
matrix[i*n_rows+j] = i*j;
}
}
}

int main() {

int n_rows, n_cols;
int *matrix;

/* obtain values for n_rows & n_cols */

/* allocate the matrix */
matrix = malloc(n_rows * n_cols * sizeof *matrix);

/* use the array */
initMatrix(matrix, n_rows, n_cols);

/* deallocate the array */
free(matrix);

}
```