如果我尝试在 C 中将一个数组复制到另一个数组中,则会出现错误消息

Error message if I try to copy one array into another in C

如果我尝试使用赋值运算符将一个数组复制到另一个数组,编译器会给我一条错误消息。这是为什么?

虽然这对我来说看起来不错,但作业,

a = b; //a和b是数组

是非法的。是否有一种仅使用某种 for 循环将一个数组复制到另一个数组的简单方法?

编辑 在小数组的情况下,memcpy 是否优于循环?

如果是 int 数组,请不要忘记包含 <string.h>:

int * intdup(int const * src, size_t len)
{
   int * p = malloc(len * sizeof(int));
   memcpy(p, src, len * sizeof(int));
   return p;
}

你不能直接做array1 = array2。因为在这种情况下,您将操纵数组的地址而不是它们的值

.. Even though this looks good to me,

等等,到此为止。数组不可赋值。您不能将数组类型变量用作赋值运算符的 LHS 操作数。

我强调,引用 C11,章节 §6.5.16

An assignment operator shall have a modifiable lvalue as its left operand.

并且,来自 §6.3.2.1

.... A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

您需要

  • 遍历单个数组元素并一一赋值(如果元素本身是数组,递归地使用这个理论)
  • 使用memcpy().

也就是说,"is memcpy preferred over a loop in case of small arrays?"没有一个确定的答案。您需要检查生成的汇编代码以确保。启用适当的优化后,编译器可能会在两种大多数情况下选择最佳的。

/* Copying data from array 'a' to array 'b */
   for (i = 0; i < num; i++) {
  arr2[i] = arr1[i];
 }

不能在 C++ 中将数组分配给另一个数组对象或从另一个数组对象初始化数组,因为它们在 C 中不能,而且由于历史原因它们不能在 C 中不再真正相关。

在很早的时候 proto-C,对于像 int a[] = {0}; int b[] = {0};一 = b;应该将数组 b 的内容复制到 a,或者 re-seat 名称 a 来引用 b。与初始化类似,a 应该是 b 的副本还是别名。这种歧义已经存在了 40 年:很快就清楚了,如果允许它,那么 C(和 C++)中的合理含义是它应该复制,但 C 中的数组从未被制成 "proper" 值类型。

没有技术原因说明它不可能,例如,您可以分配一个以数组作为数据成员的结构类型。该标准根本没有将您的代码定义为正确的 C++。