Why are arrays not assignable in C/C++? [duplicate]

拜拜、爱过 提交于 2019-11-27 23:26:39

问题


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 and b evaluate to pointer values in that context; it's equivalent to writing 3 = 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!