Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an unsigned char array of variable length?

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"

like image 275
Rich G. Avatar asked Mar 25 '13 15:03

Rich G.


2 Answers

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
};
like image 113
john Avatar answered Sep 18 '22 05:09

john


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}
};
like image 35
André Bergner Avatar answered Sep 22 '22 05:09

André Bergner