Why Can't I Assign an Array Variable Directly to Another Array Variable with the '=' Operator

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

/* 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++.

Problem with assigning an array to other array in Java

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

Why can't C assign an array directly but can assign an array in a struct?

A consequence of the historical development of C is that you cannot refer to arrays directly.

In arr2 = arr1;, both arr2 and arr1 name an array. But there is a rule in C that says when an array is used in an expression, it is automatically converted to a pointer to its first element, with certain exeptions.1 C is certainly capable of copying one array to another, as with memcpy(arr2, arr1, sizeof arr2);. The problem is there is simply no way of referring to the array in an assignment statement.

This automatic conversion of arrays was made to provide convenience for accessing elements of array and working with arrays in the ways that were used when the C language was first being developed. It was not anticipated there would be a need to refer to the entire array as a whole object, and nothing was built into the language for that. (Even today, it is not necessary—there are few operations we want perform on an array as a single object, other than copying it.)

Early C implementations also would not let you copy structures by assignment. C was a fairly basic language, providing just simple operations, and copying entire structures would have been a fancy thing. Later, the ability to copy structures was added.

In f2 = f1;, f2 and f1 refer to the structures, and there is no rule about them being automatically converted to anything, as there is for the arrays.

So the problem is simply a matter of being able to express the desired operation.

Footnote

1 The rule is in C 2018 6.3.2.1 3, and the exceptions are when the array is the operand of sizeof or unary & or is a string literal that is used to initialize an array (as in char x[] = "abc";"abc" is a string literal, which is an array).

Why is not possible to assign a pointer to an array?

In your code, one is a variable of type array. Thus,

 one = real;

is attempt to assign to an array type, which is not allowed.

To elaborate, array names are no modifiable lvalues and assignment operator only works on modifiable lvalues as the LHS operand.

Quoting C11, chapter §6.5.16

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

and then, chapter §6.3.2.1, (emphais mine)

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 use strcpy() to copy the content to the array.

Assign array to array

Arrays have a variety of ugly behavior owing to C++'s backward compatibility with C. One of those behaviors is that arrays are not assignable. Use std::array or std::vector instead.

#include <array>
...
std::array<int,5> numbers = {1,2,3};
std::array<int,5> values = {};
values = numbers;

If, for some reason, you must use arrays, then you will have to copy the elements via a loop, or a function which uses a loop, such as std::copy

#include <algorithm>
...
int numbers[5] = {1, 2, 3};
int values[5] = {};
std::copy(numbers, numbers + 5, values);

As a side note, you may have noticed a difference in the way I initialized the values array, simply providing an empty initializer list. I am relying on a rule from the standard that says that if you provide an initializer list for an aggregate, no matter how partial, all unspecified elements are value initialized. For integer types, value initialization means initialization to zero. So these two are exactly equivalent:

int values[5] = {0, 0, 0, 0, 0};
int values[5] = {};

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:")) #Stored in namelist[0]
namelist.append(input('Please enter name 2:')) #Stored in namelist[1]
namelist.append(input('Please enter name 3:')) #Stored in namelist[2]
namelist.append(input('Please enter name 4:')) #Stored in namelist[3]
namelist.append(input('Please enter name 5:')) #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Can't assign array using array member variable

There seems to be an issue with passing array parameters to class properties.

You can get around this by switching the Let parameter to a Variant:

Public Property Let avry(ByRef arrVal As Variant)
Dim i As Integer
If IsArray(arrVal) Then
ReDim pary(LBound(arrVal) To UBound(arrVal))
For i = LBound(arrVal) To UBound(arrVal)
pary(i) = arrVal(i)
Next i
End If
End Property


Related Topics



Leave a reply



Submit