Passing a two dimensional array to a function

Go4Expert Member
18Dec2007,10:31   #1
bashamsc's Avatar
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
Newbie Member
18Dec2007,15:02   #2
kv.santosh's Avatar
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
Go4Expert Founder
18Dec2007,18:01   #3
shabbir's Avatar
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
Ambitious contributor
18Dec2007,19:40   #4
Salem's Avatar
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.