3

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.

5
  • 2
    Arduino is not in C. It's in C++. Commented Sep 8, 2021 at 9:43
  • Does this answer your question? C++ error: "taking address of temporary array" Commented Sep 8, 2021 at 9:44
  • @KamilCuk, is this different in C? Commented Sep 8, 2021 at 9:52
  • 1
    @Juraj Yes, this code compiles in C but not in C++. Commented Sep 8, 2021 at 9:53
  • what is your compiler? "compound literals" are not temporaries but rather unnamed local/global variables. Is it a compiler bug? Commented Sep 8, 2021 at 10:09

1 Answer 1

6

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, "\x00\x01\x00\x00\x01", sizeof(updateArea));
    

    which will copy the bytes directly.

Sign up to request clarification or add additional context in comments.

1 Comment

probably better to declare newArray as static const so the code generation is (presumably) more efficient. Otherwise the compiler may initialize this temporary variable every time the function is called and then copy it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.