Idan
Idan

Reputation: 227

Using 2-dimensional char-array with a function

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.

Upvotes: 3

Views: 78

Answers (4)

YYJ
YYJ

Reputation: 51

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!

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34583

Suppose you have an array

char arr[3][4];

and define the function as

void board(char mat[][4])

The array decays to a pointer, so if the function wants to access mat[2][1] then the offset from the pointer will be row x width + column elements, so 2 * 4 + 1 = 9. Note that arrays are always contiguous, no matter how many dimensions.

But if you define the function as

void board(char mat[][])

then there is no information except the pointer, and the compiler has no idea how to index the array.

The reason the dimension given has to be the number of columns, is because that is the way the array is laid out in memory, row by row.

Upvotes: 0

alk
alk

Reputation: 70981

void board(char mat[][MAX_COLUMNS]);

is equivalent to

void board(char (*mat)[MAX_COLUMNS]);

with char (*mat)[MAX_COLUMNS] being the type your 2D-array is decayed to when passed to board(): To a pointer to its 1st element, as done to any array passed to a function.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149165

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.

Upvotes: 2

Related Questions