How to Pass 2D Array to Function in C: Syntax and Example
In C, you can pass a 2D array to a function by specifying the array parameter with fixed column size, like
void func(int arr[][COLS]). You must provide the number of columns so the compiler knows the memory layout. Alternatively, you can use pointers with manual indexing.Syntax
To pass a 2D array to a function, you declare the function parameter with the number of columns fixed. The number of rows can be left unspecified.
- int arr[][COLS]: The 2D array parameter where
COLSis the fixed number of columns. - int rows: Usually passed separately to know how many rows the array has.
This tells the compiler how to access elements in memory correctly.
c
void printArray(int arr[][3], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 3; j++) { printf("%d ", arr[i][j]); } printf("\n"); } }
Example
This example shows how to define a 2D array, pass it to a function, and print its elements.
c
#include <stdio.h> void printArray(int arr[][3], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 3; j++) { printf("%d ", arr[i][j]); } printf("\n"); } } int main() { int myArray[2][3] = {{1, 2, 3}, {4, 5, 6}}; printArray(myArray, 2); return 0; }
Output
1 2 3
4 5 6
Common Pitfalls
Common mistakes when passing 2D arrays include:
- Not specifying the number of columns in the function parameter, which causes a compilation error.
- Confusing rows and columns sizes.
- Trying to pass a 2D array as
int **arr, which does not work for true 2D arrays.
Always fix the column size in the function parameter.
c
/* Wrong way: missing column size */ // void printArray(int arr[][], int rows) { /* error */ } /* Correct way: specify columns */ void printArray(int arr[][3], int rows) { /* ... */ }
Quick Reference
| Concept | Example |
|---|---|
| Function parameter with fixed columns | void func(int arr[][4], int rows) |
| Passing array and rows | func(myArray, 3); |
| Access element inside function | arr[i][j] |
| Cannot omit column size | void func(int arr[][], int rows) // error |
| 2D array declaration | int myArray[2][3]; |
Key Takeaways
Always specify the number of columns when passing a 2D array to a function in C.
Pass the number of rows separately to know the array size inside the function.
Do not use int** to represent a 2D array; it is not the same as int[][] in C.
Use nested loops to access elements inside the function using arr[i][j].