在C查找表 [英] lookup table in c

查看:203
本文介绍了在C查找表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个在C查找表
当我定义的:

I'm creating a lookup table in C When I define this:

typedef struct {
 char* action;
 char* message;
} lookuptab;

lookuptab tab[] = {
  {"aa","bb"},
  {"cc","dd"}
};

它编译没有错误,但是当我做这样的事情:

it compiles without errors but when I do something like this:

typedef struct {
 char* action;
 char* message[];
} lookuptab;

lookuptab tab[] = {
  {"aaa", {"bbbb", "ccc"}},
  {"cc", {"dd", "eeeee"}}
};

我收到以下错误:

I get the following error:

错误:灵活的初始化
  数组成员在嵌套上下文

error: initialization of flexible array member in a nested context

错误:(近初始化
  标签[0] .message')

error: (near initialization for ‘tab[0].message’)

我怎么能初始化在第二个例子中的标签阵列?
注:我知道的标签阵列内的所有值

How can I initialize the tab array in the second example? Note: I know all the values inside the tab array.

更新:消息可能是不同的尺寸,例如

UPDATE: message could be of different size, e.g

typedef struct {
 char* action;
 char* message[];
} lookuptab;

lookuptab tab[] = {
  {"aaa", {"bbbb", "ccc", "dd"}},
  {"cc", {"dd", "eeeee"}}
};

非常感谢你。

最好的问候,
维克多

Best regards, Victor

推荐答案

您无法使用包含可变数组成员结构数组(结构)。见C99标准§6.7.2.1/ 2:

You can't use structures containing a flexible array member in an array (of the structure). See C99 standard §6.7.2.1/2:

一个结构体或联合体中不得含有的成员不完整或函数类型(因此,
  的结构不应含有自己的一个实例,但也可以包含一个指向一个实例
  本身),除了一个结构的最后一个成员与一个以上的命名构件
  可能有不完整的数组类型;这样的结构(含,可能任何工会
  递归,即这种结构的构件)不得结构的部件或
  数组的元素

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

所以,使用的char ** 来代替(担心你怎么知道有多少项有):

So, use a char ** instead (and worry about how you know how many entries there are):

typedef struct
{
    const char         *action;
    const char * const *message;
} lookuptab;

static const lookuptab tab[] =
{
    { "aaa", (const char * const []){ "bbbb", "ccc"   } },
    { "cc",  (const char * const []){ "dd",   "eeeee" } }
};

如果你没有使用C99编译器提防

This uses a C99 construct (§6.5.2.5 Compound literals) - beware if you are not using a C99 compiler.

这篇关于在C查找表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆