在arm平台上编译时c程序出错

问题描述 投票:0回答:1

在arm平台上编译简单的c程序。

typedef struct
{
    char* Case;
    int  RespCmdLen;
    unsigned char *RespCommand;

}ResponseStruct;
int main()
{
    unsigned char CommandResp[] = { 
        0x01,
        0x08, 0x07,
        0x05, 0x00,
        0x00,
        0x00,
        0x0B,
        0x00,
        0x00,
    };
    ResponseStruct CaseRespTbl[] =
    {
         /* case,           Response length,                response buffer pointer   */
         { "case1",             sizeof(CommandResp),        CommandResp},
    };

    return 0;
}

并得到错误

Error:  #24: expression must have a constant value
         { "case1",             sizeof(CommandResp),        CommandResp},
                                                            ^

但是,如果我将代码更改为

ResponseStruct CaseRespTbl[10];
CaseRespTbl[0].Case = "case1";
CaseRespTbl[0].RespCmdLen = sizeof(CommandResp);
CaseRespTbl[0].RespCommand = CommandResp;

然后它将编译没有任何问题。

有什么理由吗?

c
1个回答
1
投票

假设命令响应是不变的,我会抛弃它并使用:

ResponseStruct CaseRespTbl[] = {
    #  Case    Sz   Bytes
    { "case1", 10, "\x01\x08\x07\x05\x00\x00\x00\x0b\x00\x00" },
};

如果你愿意,你仍然可以使用sizeof,将最后的字符串放入#define,例如:

#define CMD_RESP "\x01\x08\x07\x05\x00\x00\x00\x0b\x00\x00"
ResponseStruct CaseRespTbl[] = {
    #  Case    Sz                  Bytes
    { "case1", sizeof(CMD_RESP)-1, CMD_RESP },
};

但对于不经常变化的数据,这可能不是必需的。

© www.soinside.com 2019 - 2024. All rights reserved.