Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign array to array

Tags:

c++

arrays

So I am playing around with some arrays, and I cannot figure out why this won't work.

int numbers[5] = {1, 2, 3};
int values[5] = {0, 0, 0, 0, 0};
values = numbers; 

The following error appear:

Error   1   error C2106: '=' : left operand must be l-value c:\users\abc\documents\visual studio 2012\projects\consoleapplication7\consoleapplication7\main.cpp 9   1   ConsoleApplication7

Why can't I do like that? What does the error mean?

like image 781
user2141625 Avatar asked Sep 23 '13 14:09

user2141625


People also ask

Can you assign an array to an array in C?

You cannot assign an array (here b ) by a pointer to the first element of another array (here a ) by using b = a; in C. The syntax doesn't allow that.

Can I assign an array to another array in Java?

Array in java can be copied to another array using the following ways. Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.


2 Answers

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] = {};
like image 56
Benjamin Lindley Avatar answered Sep 21 '22 21:09

Benjamin Lindley


You can't assign arrays in C++, it's stupid but it's true. You have to copy the array elements one by one. Or you could use a built in function like memcpy or std::copy.

Or you could give up on arrays, and use std::vector instead. They can be assigned.

like image 37
john Avatar answered Sep 21 '22 21:09

john