Why can't C assign an array directly but can assign an array in a struct?

A consequence of the historical development of C is that you cannot refer to arrays directly.

In arr2 = arr1;, both arr2 and arr1 name an array. But there is a rule in C that says when an array is used in an expression, it is automatically converted to a pointer to its first element, with certain exeptions.1 C is certainly capable of copying one array to another, as with memcpy(arr2, arr1, sizeof arr2);. The problem is there is simply no way of referring to the array in an assignment statement.

This automatic conversion of arrays was made to provide convenience for accessing elements of array and working with arrays in the ways that were used when the C language was first being developed. It was not anticipated there would be a need to refer to the entire array as a whole object, and nothing was built into the language for that. (Even today, it is not necessary—there are few operations we want perform on an array as a single object, other than copying it.)

Early C implementations also would not let you copy structures by assignment. C was a fairly basic language, providing just simple operations, and copying entire structures would have been a fancy thing. Later, the ability to copy structures was added.

In f2 = f1;, f2 and f1 refer to the structures, and there is no rule about them being automatically converted to anything, as there is for the arrays.

So the problem is simply a matter of being able to express the desired operation.

Footnote

1 The rule is in C 2018 6.3.2.1 3, and the exceptions are when the array is the operand of sizeof or unary & or is a string literal that is used to initialize an array (as in char x[] = "abc";"abc" is a string literal, which is an array).

Tags:

C