memcpy – taking the address of temporary array error

I am working on Arduino and trying to change the elements of an array. Before setup, I initialized the array like this:

bool updateArea[5] = { false };

And then I wanted to change the array like this:

updateArea[0] => false,
updateArea[1] => true,
updateArea[2] => false,
updateArea[3] => false,
updateArea[4] => true

by using:

memcpy(&updateArea[0], (bool []) {false, true, false, false, true}, 5);

However, I get the “taking address of temporary array” error.

I also tried to initialize the array in setup and loop functions but get the same error.

Answer

This sort of syntax is valid in C, but not in C++ – which is the language underlying the Arduino IDE.

But you have a few easy solutions:

  • Since you’re willing to write out the array anyways, why not just:

    bool updateArea[5] = {false, true, false, false, true};
    
  • You can declare the array as a non-temporary array and then pass it to memcpy:

    static const bool newArray[5] = {false, true, false, false, true};
    memcpy(updateArea, newArray, sizeof(updateArea));
    
  • If you can assume that sizeof(bool) == 1, then you can use this hacky solution:

    memcpy(updateArea, "x00x01x00x00x01", sizeof(updateArea));
    

    which will copy the bytes directly.