c++ - 数组赋值

标签 c++ arrays

让我用一个例子来解释-

#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/

相关文章:

c# - 使用 BinaryReader 在 C# 中读取序列化的 C++ 结构

c++ - 在二维数组中设置一个值会导致数组中的其他值发生变化

python - 如何根据 python 中另一个数组中的关键字查找数组中的字符串?

c - 在 C 中的其他输出之间打印数组元素

php - 在 MySQLi 和 PHP 中使用数组

c++ - 使用类中的 get 方法返回一个指针并使用 *& 递归地接受它

c++ - ofstream的close方法是否也关闭底层句柄

c++ - 无法使用 sizeof(成员变量)在 Visual Studio 中初始化静态常量值

python ,numpy : Setting the values for an entire 2D plane of a 3D array

arrays - 如何将数组转换为逗号分隔的字符串?