问题
I understand that the C standard prohibits the use of arrays as (modifiable) lvalues, that is, on the left-hand side of an assignment:
int lhs[4], rhs[4] = {0, 1, 2, 3};
lhs = rhs; /* illegal! */
Now, I have been wondering why this is the case. I could see the statement above (and any other assignment that writes to an array) being defined equivalent to
memcpy((void *) lhs, (void *) rhs, sizeof(lhs));
and imposing the burden of assuring that rhs
is large enough to the user, but it wasn't decided this should be the case.
However, a very similar example does work perfectly fine:
struct { int a[4]; } lhs, rhs = {{0, 1, 2, 3, 4}};
lhs = rhs;
Just by wrapping the array in a structure, we can obtain exactly the behaviour described above, that is, the assignment lhs = rhs
is equivalent to:
memcpy((void *) &lhs, (void *) &rhs, sizeof(lhs));
What is the rationale for this (as I feel) inconsistency? Is there any problem with allowing array assignments interpreted as memcpy
s?
回答1:
C is supposed to be a low level language, not hiding potentially memory or time consuming tasks behind simple syntax. One operator generates one assembly instruction; for more complicated stuff call a function. In early C you couldn't assign structs either, nor pass them between functions (you'd pass a pointer).
EDIT:
A struct is one value. Its size is static and known at compile time. An array is multiple values, and most arrays are dynamically allocated/reallocated. Their size isn't known at compile time so the compiler won't know how much memory to allocate and copy.
int *a, *b;
a = malloc(/* value based on e.g. user input */);
b = a; /* compile this into what? */
For it to work, C would have to internally store an array's size together with the pointer or together with the data pointed to. This decision was left to the programmer.
来源:https://stackoverflow.com/questions/28058377/why-are-arrays-not-lvalues