Array1 = Array2 wont work

Why cant I assign one array to another array?

int array1[] = {1,2,3,4};

int array2[4];

void setup() {
// put your setup code here, to run once:
array2 = array1;
}

void loop() {
// put your main code here, to run repeatedly:

}

C-style arrays are exceptions to many rules in C++. If you can (i.e. on any board except AVR), use C++ arrays:

#include <array>

std::array<int, 4> array1 = {1,2,3,4};
std::array<int, 4> array2;

void setup() {
  array2 = array1;
}
void loop() {}

If you're stuck on AVR, you'll have to copy the elements manually using a for loop, or if they are trivially copyable types such as int, you can use memcpy.

It might be worth considering whether you actually need to copy anything. It might be more efficient to keep a pointer to the array and simply change the pointer to point to another array instead of copying all elements in the array.

Pieter

Why cant I assign one array to another array?

Because the way that you are doing it is not valid in C/C++

One way to do it is with memcpy()

int array1[] = {1, 2, 3, 4};
int array2[4];

void setup()
{
  Serial.begin(115200);
  memcpy(array2, array1, sizeof(array1));
  for (int x = 0; x < 4; x++)
  {
    Serial.println(array2[x]);
  }
}

void loop()
{
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.