Passing a two dimensional array to a function

bashamsc's Avatar, Join Date: May 2007
Go4Expert Member
I tried two methods for this and it worked.

First Method :

Code:
#include<stdio.h>

void fun(int *a,int col , int row)
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf(" %d\n",*(a+j));
}
a=a+4;
}
}


main()
{

int arr[4][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

fun(&arr[0][0],3,4);

}

Second Method :

Code:
#include<stdio.h>

void fun(int a[3][3],int col , int row)
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(" %d\t",a[i][j]);
}
printf("\n\n");
}
}


main()
{

int arr[3][3] = {{1,2,3},
                 {4,5,6},
                 {7,8,9}};
printf("%u\n",arr);
fun(arr,3,3);

}

Last edited by shabbir; 18Dec2007 at 17:56.. Reason: Code block
0
kv.santosh's Avatar, Join Date: Dec 2007
Newbie Member
Hi,

just a small correction...ur function should rather used passed row an col values insetad of hardcoding them...somehting like this....

Code:
void fun(int *a,int col , int row)
{
int i,j;
for(i=0;i<col ;i++)
{
for(j=0;j<row;j++)
{
printf(" %d\n",*(a+j));
}
a=a+row;
}
}

Last edited by shabbir; 18Dec2007 at 17:59.. Reason: Code block
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Guys learn to use code block in posts when you have code snippets in the posts. You can refer to the following thread.

http://www.go4expert.com/showthread.php?t=168
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
Learning how to indent code as well would be a priority as well.

In response to "method 1".
http://c-faq.com/aryptr/ary2dfunc2.html

> I tried two methods for this and it worked.
Be careful of thinking that "works for me" is any substitute for knowing what is guaranteed by the standard. There are hundreds (possibly thousands) of compilers out there, and you've just tested one of them with a single experiment.