parham
parham

Reputation: 21

how declaring an array as argument doesn't need a bound for the 1st dimension?

In C it's not possible to declare a 2D array as an argument without bounding the second dimension, while it's possible for the first dimension to have no bounds. I was wondering how does the compiler keeps track of the first dimension's length and why it doesn't do the same for further dimensions?

As compiling the following code wouldn't work:

int func(int array[][]) {
  return 0;
}

and would yield

error: declaration of ‘array’ as multidimensional array must have bounds for all dimensions except the first

Upvotes: 1

Views: 470

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222437

In general, the compiler does not keep track of the first dimension of an array argument/parameter. (If it does, this is an extension to what the C standard requires, possibly as part of a feature to provide bounds checking.) It is actually impossible to pass an array as an argument in C, and it is impossible for a routine to declare an array as a parameter.

When a function parameter is declared as an array, it is automatically adjusted to be a pointer, per C 2018 6.7.6.3 7:

A declaration of a parameter as “array of type” shall be adjusted to “qualified pointer to type”, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation…

When an array is given as a function argument, it is automatically converted to a pointer to its first element, per C 2018 6.3.2.1 3:

Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object…

Thus an array is never passed as an argument nor received as a parameter. Only pointers are passed.

The C implementation never needs the length of the array to provide any standard C behavior. Suppose, for example, a parameter is declared as int x[3][4]. This is automatically adjusted to be int (*x)[4]. Then, if the code in the function uses x[i][j], the C implementation needs to find that element in memory. It is i*4+j elements beyond where x points. The implementation needs the second dimension to do the calculation, because it has to increment by i subarrays to find element x[i][j]. Since it is increment by subarrays, it needs to know how big the subarrays are.

However, the C implementation does not need to know how big the array is. No expression will require it to use the size of the array. So having just the pointer to the first element of the array is enough.

Upvotes: 2

Related Questions