让我用一个例子来解释-
#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;
}
是不是因为,数组在传递给函数foo(..)
时衰减为指针,赋值操作是可能的。而在 main
中,是不是因为它们是 int[]
类型,这会使赋值操作无效。 a,b
在这两种情况下的意思不一样吗?谢谢。
编辑 1:
当我在函数 foo
中执行此操作时,它会将 b 的
起始元素位置分配给 a
。因此,从这个角度思考,是什么让语言开发人员没有在 main()
中做同样的事情。想知道原因。
最佳答案
您回答了自己的问题。
因为这些
int a[] = { 1,2 };
int b[] = { 3,4 };
类型为int[2]
。但是这些
void foo( int a[2], int b[2] )
类型为int*
。
可以复制指针,但不能复制数组。
关于c++ - 数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5279082/