c - C 语言第 2 级数组的理想数据类型

标签 c arrays static initialization

现在I found a way为了静态初始化我的项目数组,我需要一个更复杂的结构,而不是 char* 作为值,我需要一个结构(名为atom_s)。

typdef struct atom_s {
  const char *val;
  const char *filter;
} atom_t;

struct
{
  const char *key;
  const atom_t **values;
} key_to_values[] =
{
  { .key = "foo", .values = (const atom_t *[]) { NULL } },
  { .key = "bar", .values = (const atom_t *[]) { { .val = "foo", .filter = "bar" }, NULL } },
};

问题是:我不知道如何在上面的数组声明中初始化一个atom_s,或者是否可能。 数组的第二行(key = "bar")无法编译:

warning: braces around scalar initializer  
warning: (near initialization for '(anonymous)[0]')
error: field name not in record or union initializer

最佳答案

{ 
   .key = "bar", 
   .values = (const atom_t *[]) {
       (const atom_t []) {
           { .val = "foo", .filter = "bar" }
           // how is the user going to know this array has one element?
       },
       NULL 
   }
},

values 指向的数组中的每个元素都指向一个 atom_t 数组(最后一个除外,它为 null)。您可能还需要某种方法来终止每个内部数组,除非它们的长度始终相同。

关于c - C 语言第 2 级数组的理想数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13192427/

相关文章:

C++工厂实现麻烦

时间:: console application - static methods

JavaScript 变量赋值表现出奇

c - 如何为visual studio构建工具cl.exe编写makefile(nmake)

c - 如何在不影响按钮名称的情况下更改按钮中的文本?

c - 如何防止无限循环写入文件

C++:将数组的初始部分按升序排序,另一部分按降序排序

javascript - 使用闭包进行多项选择的数组过滤器函数 - Javascript

c - 将外部变量重新定义为静态时没有错误

c++ - 更改 .h 文件时是否可以重用 .so 文件