Header Ads Widget

how to pass 2d array to a function by pointer.

we can pass 2d array to a function by two methods.-

Program to find sum of all element of a aray:

1) first method:-

 #include<stdio.h>
int fun(int a[][3]); // function declaration
void main()
{
int a[3][3],i,j,total_sum;
printf("Enter array element ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
total_sum=fun(a); // function calling
printf("Sum of all element is %d",total_sum);
}

// function definition
int fun(int a[][3])
{
int i,j,sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+a[i][j];
}
}
return sum;
}

2) method second:

#include<stdio.h>
int fun(int (*p)[][3]); // function declaration
void main()
{
int a[3][3],i,j,total_sum;
printf("Enter array element ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
total_sum=fun(a); // function calling
printf("Sum of all element is %d",total_sum);
}

// function definition
int fun(int (*p)[][3])
{
int i,j,sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+(*p)[i][j];
}
}
return sum;
}


Post a Comment

0 Comments