我通读了这个(How to initialize a unsigned char array?),但它并没有完全回答我的问题。
我知道我可以像这样创建一个字符串数组:
const char *str[] =
{
"first",
"second",
"third",
"fourth"
};
如果我想写()这些我可以使用:write(fd,str [3],sizeof(str [3]));
但是如果我需要一个可变长度的无符号字符数组怎么办?我试过这个:
const unsigned char *cmd[] =
{
{0xfe, 0x58},
{0xfe, 0x51},
{0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23},
{0xfe, 0x3d, 0x02, 0x0f}
};
我得到gcc编译警告,如 *“标量初始化器周围的括号” *“初始化使得指针来自整数而不是强制转换”
答案 0 :(得分:6)
这是一种方式
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
};
答案 1 :(得分:0)
使用多维数组时,必须指定最后一个维的大小,以便编译器计算正确的地址算术。 您的cmd指针数组有两个维度。第二个维度的最大长度为6个元素,因此:
const unsigned char cmd[][6] =
{
{0xfe, 0x58},
{0xfe, 0x51},
{0xfe, 0x7c, 0x01, 0x02, 0x00, 0x23},
{0xfe, 0x3d, 0x02, 0x0f}
};
来自ANSI C标准: “如果初始化未知大小的数组,其大小由索引最大的数组决定 具有显式初始化程序的元素。在其初始化列表的末尾,不再是该数组 有不完整的类型。“
答案 2 :(得分:0)
这对我有用(用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}
};