Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array lengths in array parameters

I am reading C Programming: A Modern Approach by K.N.King to learn the C programing language and the current chapter tells about functions, and also array parameters. It is explained that one can use constructs like these to express the length of array parameters:

1.

void myfunc(int a, int b, int[a], int[b], int[*]); /* prototype */

void myfunc(int a, int b, int n[a], int m[b], int c[a+b+other_func()]) {
... /* body */
}

2.

void myfunc(int[static 5]); /* prototype */

void myfunc(int a[static 5]) {
... /* body */
}

So the question(s) are:

a. Are the constructs in example 1 purely cosmetic or do they have an effect on the compiler?

b. Is the static modifier in this context only of cosmetic nature? what exactly does it mean and do?

c. Is it also possible to declare an array parameter like this; and is it as cosmetic as example 1 is?

void myfunc(int[4]);

void myfunc(int a[4]) { ... }
like image 407
MinecraftShamrock Avatar asked Apr 27 '15 12:04

MinecraftShamrock


People also ask

How do you find the length of an array array?

With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.

Is it array length () or array length?

length vs length()The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.

How do you find an array with specific length?

One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert.

What are the parameters of an array?

A parameter array can be used to pass an array of arguments to a procedure. You don't have to know the number of elements in the array when you define the procedure. You use the ParamArray keyword to denote a parameter array.


1 Answers

The innermost dimension of function array parameters is always rewritten to a pointer, so the values that you give there don't have much importance, unfortunately. This changes for multidimensional arrays: starting from the second dimension these are then used by the compiler to compute things like A[i][j].

The static in that context means that a caller has to provide at least as many elements. Most compilers ignore the value itself. Some recent compilers deduce from it that a null pointer is not allowed as an argument and warn you accordingly, if possible.

Also observe that the prototype may have * so clearly the value isn't important there. In case of multidimensional arrays the concrete value is the one computed with the expression for the definition.

like image 93
Jens Gustedt Avatar answered Oct 10 '22 12:10

Jens Gustedt