I was coding a problem to print the elements on the diagonal and I do not understand why the first function is working and the second one is not.
Snippet 1:
void printDiag1(int size, double a[][101], int row, int col)
{
if(size<=0) return;
printDiag1(size-1,a,row,col);
printf("%lf ",a[size-1][size-1]);
}
Snippet 2:
void printDiag2(int size, double a[size][size], int row, int col)
{
if(size<=0) return;
printDiag2(size-1,a,row,col);
printf("%lf ",a[size-1][size-1]);
}
Can somebody explain me why and tell what
double a[size][size]
means in the arguments of the second function?
CodePudding user response:
In either function a
is a 2D array (array of arrays). As per the rules of function parameters, arrays passed as parameters "decay" into a pointer to their first element. That's for example the very reason you are allowed to type double a[][101]
with the left dimension empty.
So these two examples "decay" into pointers to arrays, double (*a)[101]
and double (*)[size]
respectively. The only difference is that double (*a)[101]
can only point to an array of size 101
and double (*)[size]
can only point to an array of size size
. The latter is a pointer to a variable-length array (VLA) with flexible size.
VLA can be used for increased type safety which is what's happening here. printDiag2(size-1,a,row,col);
doesn't work because a
still expects to point at an array of type double [size][size]
, so you can't pass that to a function suddenly expecting double [size-1][size-1]
.
I would strongly recommend to stay away from recursion in general. It's a pox and some 99% of all use-cases where we spot it on SO are invalid. In this case a plain for
loop would have been much faster, much more readable, less memory consuming and likely without bugs such as the one you got here.