为什么数组在 C/C++ 中不可赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25230714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:17:17  来源:igfitidea点击:

Why are arrays not assignable in C/C++?

c++carraysstructcopy-assignment

提问by Kapichu

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").

因为,严格来说,结构只是具有可变大小元素的数组,所以为什么不允许呢?无论如何,这种分配是未使用的。当然,看起来似乎只涉及地址,但可以轻松地(“静态”地)复制数组。

回答by haccks

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.

C 的编写方式是在计算数组表达式时计算第一个元素的地址。

Thisis why you can't do something like

int a[N], b[N];
a = b;

because both aand bevaluate to pointer valuesin that context; it's equivalent to writing 3 = 4. There's nothing in memory that actually storesthe address of the first element in the array; the compiler simply computes it during the translation phase1.

就是为什么你不能做这样的事情

int a[N], b[N];
a = b;

因为a和 都b评估为该上下文中的指针;相当于写3 = 4。内存中没有任何东西实际存储数组中第一个元素的地址;编译器只是在翻译阶段1期间计算它



1. Emphasis is mine.

1. 重点是我的。