Char Array Initialization With Hex Literals

Hello everyone,

When I search for how to initialize a char array with hexadecimal values people say to write this
 
unsigned char arr[] = {0x0a, 0x0b, 0x01, 0x04};


or

 
unsigned char arr[] = {'\x0a\x0b\x01\x04'};


However, when I try compiling either example with command g++ test.cpp -o test

I get this error
1
2
error: initializer for flexible array member ‘unsigned char testing::arr []’
     unsigned char arr[]={0x0a, 0x0b,0x01,0x04};


What am I doing wrong other than not explicitly specifying the length of the array?

Where can I read more about working with hex values without wrong code?
You can't use either methods to initialize array class members.

The closest option:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//A.h

class A{
    unsigned char arr[4];
public:
    A();
};

//A.cpp

A::A(){
    static const unsigned char arr_data[] = { 0x0A, 0x0B, 0x01, 0x04 };
    static_assert(sizeof(arr_data) == sizeof(this->arr), "Check your sizes!");
    memcpy(this->arr, arr_data, sizeof(arr_data));
}
Alright, thanks.

This might be a stupid question, but why can you not?
Non-static members of array type cannot deduce their size from member initialisers.
If this were allowed, it could lead to ambiguities: the member may be initialised in a different manner (with a different size) in one constructor. For example, if it were allowed:

1
2
3
4
5
6
7
struct A
{
    A() = default ;
    A( unsigned char c ) : arr{ 0, 1, 2, 3, 4, 5, 6, 7, c } {}

    unsigned char arr[] { 0x0a, 0x0b, 0x01, 0x04 };
};



This if fine; there is no ambiguity:

1
2
3
4
5
6
7
struct A
{
    A() = default ;
    A( unsigned char c ) : arr{ 0, 1, 2, 3, 4, 5, 6, 7, c } {}

    unsigned char arr[20] { 0x0a, 0x0b, 0x01, 0x04 }; // size of the array is specified
};
Topic archived. No new replies allowed.