How to pass a 2D array as a parameter in C?

In C programming, a 2D array can be passed as a parameter to a function in several ways. The method depends on whether the array dimensions are known at compile time or need to be determined at runtime.

Syntax

// Method 1: Fixed dimensions (known at compile time)
void function_name(int arr[ROWS][COLS]);

// Method 2: Variable dimensions (C99 and later)
void function_name(int rows, int cols, int arr[rows][cols]);

// Method 3: Using pointer to array
void function_name(int (*arr)[COLS]);

Method 1: Using Fixed Dimensions

When array dimensions are known at compile time, you can specify them as global constants −

#include <stdio.h>

const int R = 4;
const int C = 3;

void modifyArray(int a[R][C]) {
    int i, j;
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++) {
            a[i][j] += 5;
        }
    }
}

int main() {
    int a[R][C];
    int i, j;
    
    /* Initialize array */
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++) {
            a[i][j] = i + j;
        }
    }
    
    printf("Initial 2-D array is:
"); for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { printf("%d ", a[i][j]); } printf("
"); } modifyArray(a); printf("Modified 2-D array is:
"); for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { printf("%d ", a[i][j]); } printf("
"); } return 0; }
Initial 2-D array is:
0 1 2 
1 2 3 
2 3 4 
3 4 5 
Modified 2-D array is:
5 6 7 
6 7 8 
7 8 9 
8 9 10 

Method 2: Using Variable Length Arrays (VLA)

With C99 standard, you can pass dimensions as parameters and use Variable Length Arrays −

#include <stdio.h>

void printArray(int rows, int cols, int arr[rows][cols]) {
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("
"); } } int main() { int rows = 3, cols = 4; int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; printf("2-D Array using VLA:
"); printArray(rows, cols, arr); return 0; }
2-D Array using VLA:
1 2 3 4 
5 6 7 8 
9 10 11 12 

Key Points

  • Fixed dimensions: Use global constants when array size is known at compile time.
  • Variable Length Arrays: Pass dimensions as parameters for flexible array sizes (C99+).
  • Memory layout: 2D arrays are stored as contiguous memory blocks in row-major order.
  • Pass by reference: Arrays are automatically passed by reference, so modifications affect the original array.

Conclusion

Passing 2D arrays to functions in C can be done using fixed dimensions or Variable Length Arrays. The VLA approach provides more flexibility for different array sizes at runtime.

Updated on: 2026-03-15T10:03:44+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements