为什么不能分配相同类型和大小的数组? [英] Why can't arrays of same type and size be assigned?

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

问题描述

如果我声明两个数组 - arr1arr2 - 比如说,类型 int 每个大小为 10,并初始化第一个数组,我希望在 arr2 中创建一个 arr1 的副本;为什么我不能直接给出指令 arr2 = arr1 ?

If I declare two arrays - arr1 and arr2 - of, say, type int of size 10 each, and initialize first array, and I wish to create a copy of arr1 in arr2; why can't I just give the instruction arr2 = arr1 ?

我知道可以分配两个相同类型的结构.为什么数组不是这种情况?

I know two structures of same type can be assigned. Why is that not the case with arrays?

推荐答案

数组的问题在于,在所有表达式中(除非传递给 sizeof 和一元 & 运算符)它们转换为指向其第一个元素的指针.

The problem with arrays is that in all expressions (except when passed to the sizeof and the unary & operators) they convert to a pointer to their first element.

所以,假设你有:

int arr1[10];
int arr2[10];
...

那么如果你写一些类似的东西

Then if you write something like

arr1 = arr2;

您实际上是在尝试这样做:

you are actually attempting to do this:

arr1 = &arr2[0];

或者这个:

&arr1[0] = &arr2[0];

在这两种情况下,您都会遇到阻止代码编译的问题.在前一种情况下,您试图在两个不兼容的类型(数组与指针)之间进行分配,而在后一种情况下,您试图修改一个常量指针(&arr1[0]).

In both cases you have a problem preventing your code from compiling. In the former case you're attempting to assign between two incompatible types (array vs pointer), while in the latter case you're attempting to modify a constant pointer (&arr1[0]).

这篇关于为什么不能分配相同类型和大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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