让我用一个例子来解释 -
#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;
}
Run Code Online (Sandbox Code Playgroud)
是因为,当传递给函数时,数组衰减到指针,可以进行foo(..)赋值操作.而且main,是因为它们是int[]使赋值操作无效的类型.a,b这两种情况都不一样吗?谢谢.
编辑1:
当我在函数中执行它时foo,它会将b's起始元素位置分配给a.因此,从它的角度思考,是什么让语言开发人员不再这样做了main().想知道原因.
你是在自问自答.
因为这些
int a[] = { 1,2 };
int b[] = { 3,4 };
Run Code Online (Sandbox Code Playgroud)
有类型的int[2].但是这些
void foo( int a[2], int b[2] )
Run Code Online (Sandbox Code Playgroud)
有类型的int*.
您可以复制指针但不能复制数组.
| 归档时间: |
|
| 查看次数: |
11282 次 |
| 最近记录: |