How to initialize an unsigned char array of variable length?

21,921

Solution 1

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
};

Solution 2

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}
};
Share:
21,921
Rich G.
Author by

Rich G.

Updated on March 26, 2020

Comments

  • Rich G.
    Rich G. about 4 years

    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"

  • dchhetri
    dchhetri about 11 years
    Can you explain why the naming is needed for the subarray?
  • john
    john about 11 years
    n.m. explains it in the comments above.