- 1 year ago
How to pass a full 2D array to a function in C
Comment
1 / 1
In C, you cannot pass a full 2D array directly to a function. However, you can pass a pointer to a 2D array to achieve a similar effect. Here's an example of how you can pass a 2D array to a function in C:
c#include <stdio.h>
// Function that takes a pointer to a 2D array
void processArray(int (*arr)[3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int rows = sizeof(arr) / sizeof(arr[0]);
int cols = sizeof(arr[0]) / sizeof(arr[0][0]);
// Pass the array to the function
processArray(arr, rows, cols);
return 0;
}
In the above example:
- The
processArray
function takes a pointer to a 2D array as its argument, along with the number of rows and columns. - The
main
function declares a 2D array namedarr
and initializes it with some values. - The
rows
variable is calculated by dividing the total size of the array by the size of a single row. - The
cols
variable is calculated by dividing the size of a single row by the size of an individual element. - The
arr
array is passed to theprocessArray
function along with therows
andcols
values.
Inside the processArray
function, you can access the elements of the 2D array using the provided pointer and dimensions.
Note that the number of columns (cols
) in the array is required to be known at compile time in this example. If you need a more flexible solution that supports arrays with a variable number of columns, you can use dynamic memory allocation or pass the dimensions along with the array to the function.