How to Pass 2D Array to Function in C++: Syntax and Examples
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]). Alternatively, you can use pointers or templates for more flexibility. The key is to fix the number of columns so the compiler knows the memory layout.Syntax
To pass a 2D array to a function, you must specify the number of columns so the compiler knows how to access elements. The syntax looks like this:
void functionName(type arrayName[][COLS])- whereCOLSis the fixed number of columns.- You can also use pointer notation:
void functionName(type (*arrayName)[COLS]). - The number of rows can be left unspecified because it is not needed for pointer arithmetic.
cpp
void printArray(int arr[][3], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 3; j++) { std::cout << arr[i][j] << ' '; } std::cout << '\n'; } }
Example
This example shows how to declare a 2D array, pass it to a function, and print its elements. The function receives the array and the number of rows.
cpp
#include <iostream> void printArray(int arr[][3], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 3; j++) { std::cout << arr[i][j] << ' '; } std::cout << '\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 without fixing the column size or using pointers.
Example of wrong and right ways:
cpp
// Wrong: missing column size // void printArray(int arr[][], int rows) { } // Error // Right: fixed column size void printArray(int arr[][3], int rows) { /*...*/ }
Quick Reference
| Method | Syntax | Notes |
|---|---|---|
| Fixed column size | void func(int arr[][COLS]) | Most common, simple to use |
| Pointer to array | void func(int (*arr)[COLS]) | Equivalent to fixed column size syntax |
| Using templates | template | Flexible, works with any size |
| Using double pointer | void func(int** arr) | Not for true 2D arrays, needs dynamic allocation |
Key Takeaways
Always specify the number of columns when passing a 2D array to a function in C++.
You can pass 2D arrays using fixed-size arrays, pointers, or templates for flexibility.
Not specifying column size causes compilation errors.
Passing a double pointer is not the same as passing a 2D array and requires dynamic memory.
Templates allow writing functions that accept any 2D array size without hardcoding dimensions.