Home > Software engineering >  When an array variable is passed into a function as an argument, what has been passed?
When an array variable is passed into a function as an argument, what has been passed?

Time:10-15

What are the values being passed when arguments are integer and char array respectively?

CodePudding user response:

In the call f(char a[], int v) the argument a is the address of the array (which is also the address of the first element of the array &a[0]), and v is the value, say, 42.

CodePudding user response:

Both function calls and function declarations (actually function declarators) need to be considered.

When a value (actually an lvalue) of array type is used in the argument of a function call, the lvalue is converted to a pointer to the initial element of the array. Informally, the array is said to "decay" to a pointer. This happens for most places where an array appears in an expression, except when it is the operand of the sizeof operator, or the unary & operator, or when it is a string literal used to initialize an array. Ref. C17 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 and is not an lvalue. If the array object has register storage class, the behavior is undefined.

In a function declaration, a parameter with an array type is automatically "adjusted" to a pointer type derived from the type of the array elements. Ref. C17 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. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

Taken together, the overall illusion is that parameters of array type are passed by reference, although that is not actually the case; it really is just an illusion. For example, the result of the sizeof operator used on an array parameter inside a function body is the size of the pointer type that the array parameter was "adjusted" to, not the size of the array. If the array parameter was declared with a length, the length is ignored because it is irrelevant once the array type has been adjusted to a pointer type. Putting static and a length between the [ and ] does not change this adjustment, it merely imposes a restriction on callers of the function to provide enough elements in the array.

  •  Tags:  
  • c
  • Related