【问题标题】:C99 Array InitializationC99 数组初始化
【发布时间】:2021-11-22 14:42:33
【问题描述】:

我必须使用 C99,但需要初始化一个非常稀疏的数组。大致如下:

struct MyStruct1
{
    uint8_t Id;
    char Name[20];
};

struct MyStruct1 MyStruct1List[50][512];

MyStruct1List[1][0] = {0, ""};
MyStruct1List[1][10] = {45, "asb"};

MyStruct1List[5][20] = {20, "dfsdf"};

MyStruct1List[19][70] = {987, "fgfdg"};

显然以上方法行不通。实现上述目标的最佳方法是什么?

【问题讨论】:

    标签: arrays multidimensional-array c99


    【解决方案1】:

    在 C99 中,您可以使用指定的初始值设定项。无论如何,我通常会向struct 成员推荐它,因为它是明确的。例如:

    struct MyStruct1 MyStruct1List[50][512] =
    {
        [1][0]   = {.Id = 0,   .Name = ""     },
        [1][10]  = {.Id = 45,  .Name = "asb"  },
        [5][20]  = {.Id = 20,  .Name = "dfsdf"},
        [19][70] = {.Id = 987, .Name = "fgfdg"}
    };
    
    

    如 cmets 中所述,由于为未显式初始化的成员存储零,这可能需要大量 ROM。

    另一种选择是使用复合文字表达式来单独分配成员:

    MyStruct1List[1][0]   = (struct MyStruct1 ){.Id = 0,   .Name = ""     };
    MyStruct1List[1][10]  = (struct MyStruct1 ){.Id = 45,  .Name = "asb"  };
    MyStruct1List[5][20]  = (struct MyStruct1 ){.Id = 20,  .Name = "dfsdf"};
    MyStruct1List[19][70] = (struct MyStruct1 ){.Id = 987, .Name = "fgfdg"};
    

    在这种情况下,您可能希望在分配单个成员之前使用嵌套的 for 循环将数组的其余内容初始化为已知值。

    【讨论】:

    • 这在大多数实现中都有很大的不同:结构的全部内容必须从可执行文件中加载,因此可执行文件的大小将增加 525 KiB。相比之下,OP 的版本可能只需要几个字节的代码和数据来在运行时初始化特定元素。
    猜你喜欢
    • 2019-01-16
    • 2021-09-26
    • 2011-02-18
    • 2015-10-30
    • 2021-12-29
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多