数组赋值 [英] Array Assignment
问题描述
让我用一个例子解释 -
Let me explain with an example -
#include <iostream>
void foo( int a[2], int b[2] ) // I understand that, compiler doesn't bother about the
// array index and converts them to int *a, int *b
{
a = b ; // At this point, how ever assignment operation is valid.
}
int main()
{
int a[] = { 1,2 };
int b[] = { 3,4 };
foo( a, b );
a = b; // Why is this invalid here.
return 0;
}
是不是因为,传递给函数富(..)
,赋值操作是可能的,当数组衰变为指针。而在主
,是不是因为他们是类型 INT []
其中无效赋值操作。不 A,B
在这两种情况下指的是一样的吗?谢谢你。
Is it because, array decays to a pointer when passed to a function foo(..)
, assignment operation is possible. And in main
, is it because they are of type int[]
which invalidates the assignment operation. Doesn't a,b
in both the cases mean the same ? Thanks.
编辑1:
当我这样做是在一个函数富
,它的分配 B的
起始元素位置 A
。所以,在这方面,是什么让语言的开发者的思维无法做到在相同的main()
。想知道原因。
When I do it in a function foo
, it's assigning the b's
starting element location to a
. So, thinking in terms of it, what made the language developers not do the same in main()
. Want to know the reason.
推荐答案
您回答了自己的问题。
由于这些
int a[] = { 1,2 };
int b[] = { 3,4 };
有为int型[2]
。但这些
void foo( int a[2], int b[2] )
有类型为int *
。
您可以复制的指针,但不能复制数组。
You can copy pointers but cannot copy arrays.
这篇关于数组赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!