为什么用C语言不存在数组赋值操作,但是结构赋值呢? [英] Why array assignment operation doesn't exist but structure assignment does in C language?

查看:130
本文介绍了为什么用C语言不存在数组赋值操作,但是结构赋值呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a[10];
int b[10];

a = b; // illegal

typedef struct {
    int real;
    int imag;
    } complex;

complex c,d;
c = d; //legal

[我意识到a和b在第一种情况下是地址,但在第二种情况下是符号]

[I realize that a and b are addresses in 1st case,but symbols in 2nd case]

推荐答案

有关历史信息,这可能很有趣:

For historical info, this may be interesting: http://cm.bell-labs.com/who/dmr/chist.html

在B中,就像C一样,声明一个数组将为该数组预留内存,但是为变量提供的名称用于定义指向该数组的指针. Ritchie在C语言中对此进行了更改,以使名称是"数组,但在使用时可以衰减为指针:

In B, declaring an array would set aside memory for the array, just as C does, but the name supplied for the variable was used to define a pointer to the array. Ritchie changed this in C, so that the name "is" the array but can decay to a pointer when used:

在今天的C语言中仍然存在的规则是数组类型的值 当它们出现在表达式中时,它们被转换为指向 首先是组成数组的对象.

The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

本发明使大多数现有的B代码可以继续工作, 尽管语言的语义发生了根本性的变化.少数 为数组名称分配新值以调整其值的程序 起源很容易修复.在B和BCPL中可能发生,而在C中则没有意义.

This invention enabled most existing B code to continue to work, despite the underlying shift in the language's semantics. The few programs that assigned new values to an array name to adjust its origin—possible in B and BCPL, meaningless in C—were easily repaired.

如果在那个非常早的阶段,Ritchie定义了a = b来复制该数组,那么他试图从B移植到C的代码将不那么容易修复.按照他的定义,该代码将产生错误,并且他可以对其进行修复.如果他要用C复制数组,那么他将默默地更改复制数组的代码的含义,而不是重新使用用于访问数组的名称.

If at that very early stage, Ritchie had defined a = b to copy the array, then the code he was trying to port from B to C would not have been as easily repaired. As he defined it, that code would give an error, and he could fix it. If he'd made C copy the array, then he would have silently changed the meaning of the code to copy the array rather than reseating the name being used to access an array.

仍然存在一个问题,为什么自40年来没有添加此功能",但我认为这就是为什么它不存在的原因.实施起来会很费力,实际上会使早期版本的C 更差的,从某种意义上来说,将B和BCPL代码移植到C有点困难.所以Ritchie当然没有不做.

There's still the question, "why hasn't this feature been added in the 40 years since", but I think that's why it wasn't there to start with. It would have been effort to implement, and that effort would actually have made that early version of C worse, in the sense of being slightly harder to port B and BCPL code to C. So of course Ritchie didn't do it.

这篇关于为什么用C语言不存在数组赋值操作,但是结构赋值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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