When I declare or just write a function which takes a 2-dimensional char-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
void board(char mat[][MAX_COLUMNS]);
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically.
Because arrays are not first class objects in C. When you pass an array to a function, it decays to a pointer and the callee cannot guess the size. For a 1D array, it still allows to access elements through pointer arithmetics. But for a 2D array (an array of array) pointer arithmetics require that the size of the second level object (here a row) is known. That is the reason why the number of columns must be explicit.
In addition, Microsoft C does not support Variable Length Array, so the number of columns must be a constant.
Weather Vane pointed out well.
Plus, if you want to circumvent that restriction, use this prototype:
void board(char *mat, int rows, int columns);
And you can access it by this expression.
mat[i*columns+j]
when you want to access ith row jth column element.
Hope it helped!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With