Free Bud
Free Bud

Reputation: 766

C array of array of strings

In C, I need to statically pre-allocate an array of numbers, each associated with a different array of strings. Will a code like the following do the trick:

struct number_and_strings {
  int  nnn;
  char **sss;
}

static struct number_and_strings my_list[] = {
  {12, {"apple","banana","peach","apricot","orange",NULL}},
  {34, {"tomato","cucumber",NULL}},
  {5,  {"bread","butter","cheese",NULL}},
  {79, {"water",NULL}}
}

Upvotes: 4

Views: 2089

Answers (1)

P.P
P.P

Reputation: 121427

sss is a pointer to pointer. So an array of pointers can't be directly assigned to it. You can assign as follows using compound literals (which is a C99 feature):

static struct number_and_strings my_list[] = {
      {12, (char*[]){"apple","banana","peach","apricot","orange",NULL}},
      {34, (char*[]){"tomato","cucumber",NULL}},
      {5,  (char*[]){"bread","butter","cheese",NULL}},
      {79, (char*[]){"water",NULL}}
    };

Upvotes: 5

Related Questions