Is it possible to do something in C++ like:
uint8_t[] getSth() {
uint8_t a[2] = {5, 2};
return a;
}
uint8_t b[] = getSth();
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:
b
is known at compile time, use std::array<uint8_t,2>
as your return type, and as the type of b
. b
is not known at compile time (eg getSth
is in a different library) use std::vector<uint8_t>
b
is 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.