为什么不能相同类型和大小的数组分配? [英] Why can't arrays of same type and size be assigned?
问题描述
如果我声明了两个数组 - ARR1
和 ARR2
- 的,比如说,键入 INT
尺寸10各,并初始化第一个数组,我希望在 ARR2 创建
ARR1
的副本code>;为什么我不能只是给了指令 = 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?
推荐答案
对数组的问题是,在所有前pressions(当传递到除的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];
在这两种情况下,你有问题$ P $进行编译pventing您code。在前一种情况下,你要尝试两个不兼容的类型(数组指针VS)之间的分配,而在后一种情况下,你正在试图修改常量指针(&放大器; 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屋!