Home »
C programs »
C user-defined functions programs
C program to pass two dimensional array (Two-D array) to a function
Here, we have a C program, in which we are demonstrating an example of passing two dimensional arrays to a function.
Submitted by IncludeHelp, on March 22, 2018
Problem statement
Given a two dimensional array and we have to pass it to the function in C.
In this example, we are declaring a two dimensional array inside the main() function and passing it to the function - within the function, elements of the array are printing.
Function Declaration
Here is the function that we are using in the program,
void arrayfun(int ptr[3][3] , int row, int col)
Here,
- void is the return type of the function.
- arrayfun is the name of the function.
- int ptr[3][3] an integer type of variable (which is declared as two dimensional array), that will store the elements of the array which will be passed. We can also use int ptr[][3] there is no need to provide size for the row, but number of maximum columns must be provided.
- int row, int col are the variables that will store the value of number of rows and columns.
Function Calling
Function calling statement,
arrayfun(array,3,3);
Here,
- array is a two dimensional integer array
- 3,3 are the number of rows and columns
Program to pass two dimensional arrays in C
/*
C program to pass 2D array to a function
*/
#include <stdio.h>
// function to print 1D array elements
void arrayfun(int ptr[3][3] , int row, int col)
{
int i=0,j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("\nArray [%d][%d] : %d",i,j,ptr[i][j]);
fflush(stdout);
}
printf("\n");
}
}
// main function
int main()
{
// Declare a 2D array and initialize the three rows
int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
// Passing 2D-array and number of columns and rows to Function
arrayfun(array,3,3);
return 0;
}
Output
Array [0][0] : 1
Array [0][1] : 2
Array [0][2] : 3
Array [1][0] : 4
Array [1][1] : 5
Array [1][2] : 6
Array [2][0] : 7
Array [2][1] : 8
Array [2][2] : 9
C User-defined Functions Programs »