0

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

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

uint8_t b[] = getSth();
4
  • 5
    Use a std::array instead? Commented Aug 6, 2016 at 9:31
  • @Ryan I'm new. How I can use it? Commented Aug 6, 2016 at 9:31
  • No, return a will lead to undefined behavior, and uint8_t b[] = getSth() won't even compile. Commented Aug 6, 2016 at 9:32
  • en.cppreference.com/w/cpp/container/array Commented Aug 6, 2016 at 9:33

1 Answer 1

3

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.

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

Comments

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.