微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么不存在数组赋值操作但是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是第一种情况下的地址,但是第二种情况下的符号]

解决方法

对于历史信息,这可能很有趣: http://cm.bell-labs.com/who/dmr/chist.html

在B中,声明一个数组会为数组留出内存,就像C一样,但是为变量提供的名称用于定义指向数组的指针. Ritchie在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.

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复制数组,那么他就会地改变代码的含义来复制数组,而不是重新设置用于访问数组的名称.

还有一个问题,“为什么自40年以来没有添加这个功能”,但我认为这就是为什么它不是从那里开始的.这本来是努力实现的,并且这种努力实际上会使C的早期版本更糟糕,因为稍微更难将B和BCPL代码移植到C.所以当然Ritchie没有这样做.

原文地址:https://www.jb51.cc/c/119441.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐