Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a 2D array in a function in C program

Below program (a toy program to pass around arrays to a function) doesn't compile. Please explain me, why is the compiler unable to compile(either because of technical reason or because of standard reason?)

I will also look at some book explaining pointers/multi dimensional arrays(as I am shaky on these), but any off-the-shelf pointers here should be useful.

void print2(int ** array,int n, int m);

main()
{
    int array[][4]={{1,2,3,4},{5,6,7,8}};
    int array2[][2]={{1,2},{3,4},{5,6},{7,8}};
    print2(array,2,4);
}

void print2(int ** array,int n,int m)
{
    int i,j;
    for(i=0;i<n;i++)
    {
       for(j=0;j<m;j++)
       printf("%d ",array[i][j]);

       printf("\n");
    }
}
like image 532
xyz Avatar asked Jun 12 '11 11:06

xyz


2 Answers

This (as usual) is explained in the c faq. In a nutshell, an array decays to a pointer only once (after it decayed, the resulting pointer won't further decay).

An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.

Easiest way to solve it:

int **array; /* and then malloc */
like image 137
cnicutar Avatar answered Sep 30 '22 19:09

cnicutar


In C99, as a simple rule for functions that receive "variable length arrays" declare the bounds first:

void print2(int n, int m, int array[n][m]);

and then your function should just work as you'd expect.

Edit: Generally you should have a look into the order in which the dimension are specified. (and me to :)

like image 40
Jens Gustedt Avatar answered Sep 30 '22 18:09

Jens Gustedt