lookup table in c

前端 未结 4 2079
误落风尘
误落风尘 2021-01-03 00:58

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

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

lookuptab tab[] = {
  {\"aa\",\"bb\"},
           


        
4条回答
  •  感情败类
    2021-01-03 01:20

    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.

    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" } }
    };
    

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

提交回复
热议问题