加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的数组上使用的等式和赋值运算符

发布时间:2020-12-16 05:19:24 所属栏目:百科 来源:网络整理
导读:我被给了一个真的让我困惑的家庭作业问题.问题是: In C++ the equality test == may be applied to arrays,but the assignment operator = cannot be applied to arrays. Explain why. 这使我感到困惑,因为我的理解是,==运算符只是比较前两个元素的地址(如
我被给了一个真的让我困惑的家庭作业问题.问题是:

In C++ the equality test == may be
applied to arrays,but the assignment
operator = cannot be applied to
arrays. Explain why.

这使我感到困惑,因为我的理解是,==运算符只是比较前两个元素的地址(如果两个数组实际上位于单独的存储单元中的话)当然会有所不同).而=运算符,当使用像array1 = array2;只会导致array1指向与array2相同的内存位置.

我在这里缺少什么?似乎可以使用任何一个操作符,但也不会产生这些操作符通常意图的结果.

解决方法

my understanding is that the == operator would just compare the addresses of the first two elements

这是正确的:如果使用==比较两个数组,它将比较数组的地址,因此如果将数组与自身进行比较(或指向同一类型的元素的指针),则它将仅产生true.看到下面的描述为什么.

the = operator,when used like array1 = array2; would just cause array1 to point to the same memory location as array2 does.

这是不正确的,因为数组不是一个指针. array1不能指向与array2相同的内存位置,因为array1不是一个指针,它是一个元素数组.

数组是一系列元素.在大多数情况下,数组的名称将隐式转换为指向其初始元素的指针.这就是为什么你可以做如下事情:

void f(int*);

int data[10];
int* p = data; // this is the same as 'int* p = &data[0];'
f(data);       // this is the same as 'f(&data[0]);'

array1 = array2;将不会工作,因为数组是不可分配的(主要是出于历史原因;我从来没有听说过这样一个令人信服的技术原因:为什么它是不允许的:C在C中是不允许的,C已经存在了几十年了,有一些讨论这在Why does C support memberwise assignment of arrays within structs but not generally?的评论和答案).

以下程序将不会编译:

int main() {
    int a[10],b[10];
    a = b;
}

对于“可分配”数组,可以使用Boost(boost :: array),C TR1(std :: tr1 :: array)或C 0x(std :: array)中的数组容器类.它实际上是一个包含数组的类;它可以被复制,它提供了标准库容器的许多好处以及数组的性能特征,并且在需要时可以使用其数据作为数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读