1

I realise this has probably been done before but searching has turned up blank for this specific wrinkle.

If we want to define an array containing some strings, we can do:

char *strings[] = {"one","two","three"};

And if we want to define an array of arrays of strings, we can do:

char *strings[][] =
{
  {"one","two","three"},
  {"first","second","third"},
  {"ten","twenty","thirty"}
};

But I can't seem to do this:

char *strings[][] =
{
  {"one","two"},
  {"first","second","third","fourth","fifth"},
  {"ten","twenty","thirty"}
};

Doing that throws compiler errors.

(Examples from string initialization in multidimensional array)

Community
  • 1
  • 1
John U
  • 2,886
  • 3
  • 27
  • 39

1 Answers1

2

From here,

char *strings[][] 

strings is a 2D array.

Incase of,

char *strings[][] =
{
  {"one","two","three"},
  {"first","second","third"},
  {"ten","twenty","thirty"}
};

The compiler automatically determines the no of columns in strings. In this case each strings[i] is a row in the 2D array. Also, its a pointer (array names are pointers) of type char (*string)[3] i.e. to char array of sixe 3.

char *strings[][] =
{
  {"one","two"},
  {"first","second","third","fourth","fifth"},
  {"ten","twenty","thirty"}
};

In this case, the compiler can't create an array (the array has to have elements of same type) because strings[0] would be of type char (*strings)[2], strings[1] would be of type char (*strings)[5] and strings[2] would be of type char (*strings)[3]

Hence, the compiler says incomplete element type.

You need to specify the number of columns (N) at declaration(which will make each row of type char (*string)[N]) or assign dynamically.

Community
  • 1
  • 1
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59