How to pass two dimensional Arrays in C Programming

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/01/pass-two-dimensional-arrays-c-programming/

We can also pass two-dimensional arrays as parameters to a function. While passing two-dimensional arrays as parameters you should keep in mind the following things:

  1. In the function declaration you should write two sets of square brackets after the array name. You should specify the size of the second dimension i.e., the number of columns.
  2. In the function call you should write two sets of square brackets after the array name. Also you should specify the size of the second dimension i.e., the number of columns.

In the function call, it is enough to pass the name of the array as a parameter. No need to mention the square brackets.

#include <stdio.h>
const int n = 3;

void print(int arr[][n], int m)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr, 3);
    return 0;
}

We can also pass arrays as parameters to the called function. While passing one-dimensional array to a function, you should follow three rules. They are:

  1. In the function declaration you should write a pair of square brackets [ ] beside the name of the array. No need to specify the size of the array.
  2. In the function definition you should write a pair of square brackets [ ] beside the name of the array. Again no need to specify the size of the array.
  3. In the function call, it is enough to just pass the array name as the actual parameter. No need to write the square brackets after the array name.

When an array is passed as an actual parameter, the formal parameter also refers to the same array which is passed as an actual parameter. When passing an array as a parameter, you are passing the address of the array, not the values in the array. So, if you make changes in the array using the formal name of the array, the changes are also reflected on the actual array.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/01/pass-two-dimensional-arrays-c-programming/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger