Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Passing a two dimensional array to a function (http://www.go4expert.com/forums/passing-dimensional-array-function-t7901/)

bashamsc 18Dec2007 10:31

Passing a two dimensional array to a function
 
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);

}


kv.santosh 18Dec2007 15:02

Re: Passing a two dimensional array to a function
 
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;
}
}


shabbir 18Dec2007 18:01

Re: Passing a two dimensional array to a function
 
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

Salem 18Dec2007 19:40

Re: Passing a two dimensional array to a function
 
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.


All times are GMT +5.5. The time now is 01:57.