c pass two dimensional array to function

Passing a Two-Dimensional Array to a Function in C

To pass a two-dimensional array to a function in C, you can use a pointer to an array. Here are the steps to do it:

  1. Declare the function prototype: Start by declaring the function prototype, which includes the function name, return type, and parameter list. In this case, the parameter should be a pointer to a two-dimensional array. The syntax for declaring a pointer to a two-dimensional array is data_type (*pointer_name)[num_columns].

  2. Define the function: Define the function and specify the parameter as a pointer to a two-dimensional array. You can use any valid identifier for the pointer name. Inside the function, you can access the elements of the array using the pointer notation.

  3. Pass the array to the function: When calling the function, pass the two-dimensional array as an argument. Since arrays decay into pointers when passed to functions, you don't need to use the address-of operator (&) when passing the array.

Here's an example that demonstrates these steps:

#include <stdio.h>

// Function prototype
void printArray(int (*arr)[3], int rows);

// Function definition
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 arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

    // Call the function
    printArray(arr, 2);

    return 0;
}

In this example, we have a two-dimensional array arr with 2 rows and 3 columns. We pass this array to the printArray function, which takes a pointer to a two-dimensional array as a parameter. Inside the function, we use the pointer notation arr[i][j] to access the elements of the array.

When you run this program, it will output:

1 2 3
4 5 6

This demonstrates how to pass a two-dimensional array to a function in C.