0

In C language, an array cannot be copied to another array directly by assignment operator.

int arr1[]={1,3,2};
int arr2[]={0};

arr2=arr1;//not possible

Also, we cannot assign values to an array that is already defined, if I am not wrong...

int a[3];
a[]={1,3,2}; //this is not possible

In the code above, a[] and {1,3,2} act as two different arrays, and an assignment operator is used between them. So, is this following the same case mentioned at the first?

Please clarify. Thanks.

  • 1
    "not allowed" is the wrong term. It is just not possible. But you don't copy an array (presuming `arr1` and `arr2` are 1D arrays), but a single element. **This** is very well possible. Please clarify your question. From a wrong prerequisite, everything can be deduced. – too honest for this site Feb 24 '16 at 11:09
  • `memset` or `memcpy` will help you to achieve the same thing though: `memcpy(arr1, arr2, sizeof arr1/sizeof *arr1);` or something – Elias Van Ootegem Feb 24 '16 at 11:10
  • That gave me some info. Thanks @Olaf – Bhanu Prakash Feb 24 '16 at 11:10

3 Answers3

1

is this following the same case mentioned at the first?

No, they are different.

In the first case, what you try to do is array assignment, which is not possible in C directly. The language grammar states an array name to be a non-modifiable lvalue, so

arr1 = arr2;

is invalid. The relevant excerpt from the C11 standard draft (§6.3.2.1):

A modifiable lvalue is an lvalue that does not have array type, ...

In the second case

int a[3];
a[]={1,3,2};

you are trying to assign the initializer list {1, 2, 3} to an invalid sub-expression a[] and hence is illegal. What is assigned to it is immaterial; a[] = 1 is invaild too.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
0

It's not quite the same.

{1,2,3} is an initializer list. The compiler sees it and hard-codes its values into the array. Assigning an initializer-list to an array that already has a definition (int array[3]; array={1,2,3};) is a syntax error (clang says expected expression because it's expecting a closing square bracket before an assignment operator as in int array[]={1,2,3};).

Assigning one array to another is impossible in your case because array type 'int [3]' is not assignable. I'd call it something like logic error (the programmer just didn't know he can't do it, but the syntax is valid).

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

The other posts and comments are correct in that you cannot assign a bare array after initialization.

However, you can assign to a struct that contains such an array, even after initialization, using a compound literal,

typedef struct {
  int v[3];
} A;

A a = {{1,2,3}};   // Valid.
a = (A){{4,5,6}};  // Also valid.
jamieguinan
  • 1,640
  • 1
  • 10
  • 14