Szymon Marczak Szymon Marczak - 4 months ago 6
C++ Question

Set an array from array function in C++

Is it possible to do something in C++ like:

uint8_t[] getSth() {
uint8_t a[2] = {5, 2};
return a;
}

uint8_t b[] = getSth();

Answer

No, not like that: built-in arrays decay to pointers on return, so you would end up with multiple errors and a hanging pointer.

C++ offers several solutions, though:

  1. If the size of bis known at compile time, use std::array<uint8_t,2> as your return type, and as the type of b.
  2. If the size of b is not known at compile time (e.g. getSth is in a different library) use std::vector<uint8_t>
  3. If the size of bis known at compile time, and you are restricted on the library functions that you are allowed to use, you can wrap your array in a struct or a class. This is the most indirect way of doing it, so I would prefer 1 or 2 instead.


std::array<uint8_t,2> getSth() {
    std::array<uint8_t,2> a = {5, 2};
    return a;
}

std::array<uint8_t,2> b = getSth();

Demo.