As per this https://stackoverflow.com/a/3912959/1814023 We can declare a function which accepts 2D array as
void func(int array[ROWS][COLS]).
And as per this, http://c-faq.com/aryptr/pass2dary.html they say "Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, NROWS, can be omitted. The width of the array is still important, so the column dimension NCOLUMNS (and, for three- or more dimensional arrays, the intervening ones) must be retained."
I tried this and it works... Note that I have changed the size of column.
#include <stdio.h>
#define ROWS 4
#define COLS 5
void func1(int myArray[][25])
{
int i, j;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
myArray[i][j] = i*j;
printf("%d\t",myArray[i][j]);
}
printf("\n");
}
}
int main(void)
{
int x[ROWS][COLS] = {0};
func1(x);
getch();
return 0;
}
My question is, why in the CFAQ link(http://c-faq.com/aryptr/pass2dary.html) they say "The width of the array is still important"? even though I have provided wrong column size.
Can someone please explain?
int(*)[5](after decay, of course) as aint(*)[25].index = col. When row is 0, the width is unimportant. However to access an element on any other row, you must also know the number of columns wide it is, since the equation then becomesindex = row*numCols + col- So, what you've done should crash. If it doesn't, it's just luck each time you execute it. The idea of setting COLS to 25 means that when i=ROWS-1 and j=COLS-1, means that for the last element, index is calculated asindex = (4-1)*25 + (5-1)!! Baaaad!func()but definesfunc1(). So the called function isn't the defined function (aka 'there is a typo in the question'). You should still get warnings (at least) for calling an undeclared function, if you use a C99 or later compiler. Since the code usesgetch(), it is probably running on Windows and therefore is using an antique C89 compiler (aka MSVC).