为什么数组不是左值? [英] Why are arrays not lvalues?

查看:134
本文介绍了为什么数组不是左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解C标准禁止将数组用作(可修改的)左值,即在赋值的左侧:

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));

并承担确保 rhs 对用户来说足够大的负担,但是并没有确定应该是这种情况.

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;

仅通过将数组包装在结构中,我们就可以准确地获得上述行为,即赋值 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));

这种(我认为)不一致的理由是什么?允许将数组分配解释为 memcpy s有任何问题吗?

What is the rationale for this (as I feel) inconsistency? Is there any problem with allowing array assignments interpreted as memcpys?

推荐答案

C应该是一种低级语言,不会在简单的语法后面隐藏潜在的内存或耗时的任务.一位操作员生成一条组装指令;对于更复杂的东西,请调用函数.在早期的C语言中,您既无法分配结构,也无法在函数之间传递结构(您将传递指针).

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

结构是一个值.它的大小是静态的,在编译时是已知的.一个数组是多个值,并且大多数数组是动态分配/重新分配的.它们的大小在编译时未知,因此编译器将不知道要分配和复制多少内存.

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? */

要使其正常工作,C必须在内部将数组的大小与指针或指向的数据一起存储.这个决定留给程序员.

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.

这篇关于为什么数组不是左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆