问题
This question already has an answer here:
- Why do C and C++ support memberwise assignment of arrays within structs, but not generally? 5 answers
One can assign a struct to another, which results in copying all the values from struct to another:
struct
{
int a, b, c;
} a, b;
...
a = b;
But why are arrays not assignable like that:
int a[3], b[3];
...
a = b;
Because, strictly speaking, are structs just arrays with variable sized elements, so why is that not allowed? This kind of assignment is unused anyway. Sure, it may seem like only the addresses are involved, but one can easily copy arrays that way ("statically").
回答1:
Quoting from this answer:
C is written in such a way that the address of the first element would be computed when the array expression is evaluated.
This is why you can't do something like
int a[N], b[N]; a = b;
because both
a
andb
evaluate to pointer values in that context; it's equivalent to writing3 = 4
. There's nothing in memory that actually stores the address of the first element in the array; the compiler simply computes it during the translation phase1.
1. Emphasis is mine.
来源:https://stackoverflow.com/questions/25230714/why-are-arrays-not-assignable-in-c-c