Possible Duplicate:
How do I use arrays in C++?
One dimensional array as a function parameter:
#include <stdio.h>
#include <string.h>
int func(int a[], int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ", a[i][j]);
}
int main(void)
{
int a[2] = {1,2};
func(a, 2);
}
it compiles and runs correctly.
But when a two-dimensional array as a function parameter:
#include <stdio.h>
#include <string.h>
int func(int a[][], int n)
{
int i, j;
for(i = 0; i < n; i++)
for(j = 0 ; j < n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
int main(void)
{
int a[2][2] = {{1,2}, {3,4}};
func(a, 2);
}
it can not compile correctly. I must modify the code like this:
#include <stdio.h>
#include <string.h>
int func(int a[][2], int n)
{
int i, j;
for(i = 0; i < n; i++)
for(j = 0 ; j < n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
int main(void)
{
int a[2][2] = {{1,2}, {3,4}};
func(a, 2);
}
I do not know why? Anybody can explain how it works? Many thanks.
Arrays (both one and multidimensional) in c reside in continuous memory blocks. This means that when you define
char a[3], the array is laid out in memory like this (forgive my terrible ascii art skills):For a two-dimensional array
char a[2][3], the layout is like this:Therefore, when you index into a two-dimensional array
a[i][j], the compiler generates code equivalent to this:Which can be read as “skip i rows and take cell j in that row”. To accomplish this, the compiler must know the length of the row (which is the second dimension). This means that the second dimension is a part of the type definition!
As such when you want pass a 2d array into a function, you must specify the needed dimension for the type definition.