I am trying to pass a two-dimensional array to a function. I am not having trouble to pass it to the function. But I am having trouble in understanding the logic behind this. The functions and main definition goes like this:
// Function to print the two-dimensional array
void print(int x, int y, int a[x][y]){
printf("\n");
int i, j;
for(i = 0; i < x; i++){
for(j = 0; j < y; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
// Function to initialize the two-dimensional array
void init_2d(int *a, int x, int y){
int i, j;
for(i = 0; i < x; i++){
for(j = 0; j < y; j++){
a[i*y + j] = i + j;
}
printf("\n");
}
}
int main(){
int m = 2, n = 3;
int a[m][n]; // a two dimensional whose size has been defined using m and n
init_2d(a, m, n);
print(m, n, a);
}
Ironically everything is working fine. And that is my problem as I am not able to digest the logic of it.
The main problems are:
- What I read in books was that the size of the two-dimensional arrays should be defined using constants or symbolic constants. In my main I am defining 2-D array using variables
m
andn
and yet it works fine. Why? - I was also told to pass the two-dimensional array by decaying it into a single dimensional array (by defining it as a pointer to int in function) i.e. the way I have done it in function
init_2d
. But in theprint
function I am doing it using a two dimensional array whose size has been defined using variablesx
andy
. Is it fine to do so? - Can a two-dimensional array be traversed using a pointer to a pointer as well?
Can anybody suggest me a good read on this topic which can clear all my concepts?
I am using codeblocks to compile my code and the compiler is GNU GCC Compiler.