【问题标题】:How to initialize an int array within a struct within another struct arrya?如何在另一个结构数组中的一个结构中初始化一个 int 数组?
【发布时间】:2017-11-09 23:47:45
【问题描述】:
struct customFunction {
    int id;
    int numOfSubfunctions;
    int subfunctions[];
};

const customFunction supportedFunctions[] = {
    {
        0x01,
        1,
        {
            0x01
        }
    },
    {
        0x02,
        2,
        {
            0x01,
            0x02
        }
    }
    ...
};

supportedFunctions 数组将用于检查将来是否支持特定功能,并用于标识要使用哪个功能等。

目前,我出现了这个错误:

“int [0]”的初始化程序太多

指向

{
    0x01
}

对于任何函数,可能有0 - n 个子函数。

【问题讨论】:

    标签: c++ arrays struct


    【解决方案1】:

    这永远不会奏效。同一数组中的多个customFunction 元素不能为其subfunctions[] 成员具有不同的大小。数组元素的大小必须相同。

    如果customFunction 元素需要具有不同大小的subfunctions[] 数组,则必须将实际数组存储在内存中的其他位置,然后指向它们,例如:

    struct customFunction {
        int id;
        int numOfSubfunctions;
        const int *subfunctions;
    };
    
    const int subfunctions_1[] = {
        0x01
    };
    
    const int subfunctions_2[] = {
        0x01,
        0x02
    };
    
    const customFunction supportedFunctions[] = {
        {
            0x01,
            1,
            subfunctions_1
        },
        {
            0x02,
            2,
            subfunctions_2
        }
        ...
    };
    

    【讨论】:

    • 这个缓存友好吗?
    • 这有关系吗?这是执行 OP 要求的唯一选择。
    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    相关资源
    最近更新 更多