2

The compiler gives me an error message if I try to copy one array into another by using the assignment operator. Why is that?

Even though this looks good to me, the assignment,

a = b; //a and b are arrays

is illegal. Is there a simple way to copy one array into another using just a for-loop of some sort?

EDIT Is memcpy preferred over a loop in case of small arrays?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

3

.. Even though this looks good to me,

Wait, stop there. Arrays are not assignable. You cannot use an array type variable as LHS operand of assignment operator.

With my emphasis, quoting C11, chapter §6.5.16

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

and, from §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.

You need to either

  • Loop over individual array elements and assign them one by one (in case the elements are arrays themselves, use this theory recursively)
  • Use memcpy().

That said, "is memcpy preferred over a loop in case of small arrays?" does not have a definitive answer. You need to check the generated assembly code to make sure. With proper optimization enabled, compiler is likely to choose the best within the two most of the cases.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

In case of an int array, don't forget to include <string.h>:

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

You can't directly do array1 = array2. Because in this case you would manipulate the addresses of the arrays and not their values

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0
/* Copying data from array 'a' to array 'b */
   for (i = 0; i < num; i++) {
  arr2[i] = arr1[i];
 }

Arrays can't be assigned to or initialized from another array object in C++ because they can't in C, and they can't in C for historical reasons that aren't really relevant any more.

In very early proto-C, there would have be some confusion whether an assignment like int a[] = {0}; int b[] = {0}; a = b; should copy the contents of array b to a, or re-seat the name a to refer to b. Likewise with initialization, whether a should be a copy of b or an alias. This ambiguity hasn't existed for 40 years: it soon became clear that if it were to be allowed then the sensible meaning in C (and C++) would be that it should copy, but arrays in C were never made into "proper" value types.

There's no technical reason why it's impossible, and for example you can assign a struct type that has an array as a data member. The standard simply doesn't define your code to be correct C++.

Shobhit
  • 1,096
  • 11
  • 30