The initialization list is passed as a function parameter to the array

How to do it:

void foo(uint8_t a[]) { ... }

foo({0x01, 0x02, 0x03});

This gives me an error:

error: cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}' for argument '1'
                                                     ^
+4
source share
5 answers

The answers so far have not addressed the main issue with the question: in the signature

void foo(uint8_t a[])

anot an array, but a pointer to uint8_t. This is despite the fact that the declaration amakes it look like an array. This is even indicated by an error message:

cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}'

Therefore, you are not allowed to do this:

uint8_t *a = {0x01, 0x02, 0x03}; // Eek! Error

You cannot call foo({0x01, 0x02, 0x03});with the signature above.

I suggest you spend some time reading C-style arrays and how they are not first-class citizens in C ++.

, , , , . ! :

void foo(std::array<uint8_t, 3> const &a);
+3

, , , :

void foo(std::array<uint8_t, 3> a) { /* use a.data() instead of a */ }

foo({0x01, 0x02, 0x03}); // OK

foo({0x01, 0x02}); // Works, at least on GCC 4.9.1. The third value is set to zero.

foo({0x01, 0x02, 0x03, 0x04}); // Compilation error.
+6

.

uint8_t a[] = {0x01, 0x02, 0x03};

foo(a).

std::array, , , .

+4

:

void foo(uint8_t a[]) { ... }

- this is a function that accepts uint8_t*, not arrays - arrays are decomposed into pointers when using the function as arguments. The problem is that the list of initializers (e.g. {0x01, 0x02, 0x03}) cannot be converted to uint8_t*.

If you want to pass an arbitrary number from uint8_tto foo, an easy solution would be to use a newstd::initializer_list

void foo(std::initializer_list<uint8_t> a) { ... }

foo({0x01, 0x02, 0x03, 0x04, 0x05}); // OK - a has 5 elems in it

Or you can take a variational package and build an array from it from the inside:

template <typename... Args,
          typename = std::enable_if_t<
              all_true<std::is_convertible<Args, uint8_t>::value...>
              >>
void foo(Args... elems) {
    uint8_t a[] = {elems...};
    // ...
}

This is a little different:

foo({0x01, 0x02, 0x03}); // error
foo(0x01, 0x02, 0x03; // OK - a has 3 elems in it
+3
source

foo(std::array<uint8_t, 3>{0x01, 0x02, 0x03}.data());

0
source

Source: https://habr.com/ru/post/1598864/


All Articles