【发布时间】:2011-03-11 22:32:17
【问题描述】:
让我用一个例子来解释-
#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's 起始元素位置分配给a。所以,考虑到它,是什么让语言开发人员在main() 中没有做同样的事情。想知道原因。
【问题讨论】:
-
sizeof(a)在这些位置不同的原因相同:我不知道 :) -
数组到指针的转换很棘手。如果您愿意,请阅读:c-faq.com/aryptr/index.html
-
不要在 C++ 中使用数组,除非你有充分的理由这样做。
std::vector<>几乎可以满足您的所有需求。 -
@David Thornley - 只是出于好奇问了这个问题,这与另一篇帖子有点相关stackoverflow.com/questions/5278540/…
-
相关FAQ