C - Passing 2D Arrays to Functions

In C, you can pass two-dimensional arrays (also known as 2D arrays or matrices) to functions in a similar way to passing one-dimensional arrays. Two-dimensional arrays are essentially arrays of arrays, and they can be passed to functions as pointers to arrays. Here's an example of how to pass a 2D array to a function:

Example:


#include <stdio.h>

// Function to print the elements of a 2D integer array
void print2DArray(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 myArray[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int rows = sizeof(myArray) / sizeof(myArray[0]);
    int cols = sizeof(myArray[0]) / sizeof(myArray[0][0]);

    printf("Original 2D array:\n");
    print2DArray(myArray, rows, cols); // Passing the 2D array to the function

    return 0;
}
    

In this example:

  • The print2DArray function takes three parameters: a 2D integer array arr, the number of rows (rows), and the number of columns (cols) in the array.
  • Inside the main function, a 2D integer array myArray is defined, and the number of rows and columns is calculated using the sizeof operator.
  • The print2DArray function is called to print the elements of the 2D array.

Output:


Original 2D array:
1 2 3 
4 5 6 
7 8 9 
    

When you pass a 2D array to a function, you need to specify the number of columns as a parameter because C stores 2D arrays as contiguous rows in memory, and the function needs this information to correctly access the elements.

Just like with 1D arrays, modifications made to a 2D array inside a function are reflected in the original array because you are working with pointers to the actual array elements.

Keep in mind that C does not allow you to return entire 2D arrays from functions directly. If you need to create or modify a 2D array within a function and return it, you can do so by dynamically allocating memory for the 2D array and returning a pointer to the allocated memory.