Reputation: 61
I read through this(How to initialize a unsigned char array?), but it doesn't quite answer my question.
I know I can create an array of strings like this:
const char *str[] =
{
"first",
"second",
"third",
"fourth"
};
and if I want to write() these I can use: write(fd, str[3], sizeof(str[3]));
But what if I need an array of unsigned chars of variable length? I tried this:
const unsigned char *cmd[] =
{
{0xfe, 0x58},
{0xfe, 0x51},
{0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23},
{0xfe, 0x3d, 0x02, 0x0f}
};
and I get gcc compile warnings such as * "braces around scalar initializer" * "initialization makes pointer from integer without cast"
Upvotes: 5
Views: 25916
Reputation: 1439
This worked for me (compiles with clang & gcc):
const unsigned char *cmd[] =
{
(unsigned char[]){0xfe, 0x58},
(unsigned char[]){0xfe, 0x51},
(unsigned char[]){0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23},
(unsigned char[]){0xfe, 0x3d, 0x02, 0x0f}
};
Upvotes: 1
Reputation: 2344
When multidimensional arrays are used, you must specify the size of the last dimension in order for the compiler to calculate the proper address arithmetic. Your cmd pointer array has two dimensions. The second dimension has a maximum length of 6 elements, so:
const unsigned char cmd[][6] =
{
{0xfe, 0x58},
{0xfe, 0x51},
{0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23},
{0xfe, 0x3d, 0x02, 0x0f}
};
From the ANSI C standard: "If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. At the end of its initializer list, the array no longer has incomplete type."
Upvotes: 1
Reputation: 8027
This is one way
const unsigned char cmd1[] = {0xfe, 0x58};
const unsigned char cmd2[] = {0xfe, 0x51};
const unsigned char cmd3[] = {0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23};
const unsigned char cmd4[] = {0xfe, 0x3d, 0x02, 0x0f};
const unsigned char *cmd[] =
{
cmd1,
cmd2,
cmd3,
cmd4
};
Upvotes: 6