Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lookup table in 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

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

Thank you very much.

Best regards, Victor

like image 430
Victor Gaspar Avatar asked Oct 06 '10 18:10

Victor Gaspar


2 Answers

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.

like image 57
Jonathan Leffler Avatar answered Sep 20 '22 10:09

Jonathan Leffler


I think you have to specify the array size to use the struct in another array:

typedef struct {
 char* action;
 char* message[2];
} lookuptab;
like image 44
WildCrustacean Avatar answered Sep 20 '22 10:09

WildCrustacean