9

In Visual Studio 2010, this initialization works as expected:

char table[2][2] = {
                       {'a', 'b'},
                       {'c', 'd'}
                   };

But it does not seem legal to write something like:

char table[][] = {
                     {'a', 'b'},
                     {'c', 'd'}
                 };

Visual Studio complains that this array may not contain elements of 'that' type, and after compiling, VS reports two errors: a missing index and too many initializations.

QUESTION: Why can't I omit the dimensions altogether when initializing a multi-dimensional array?

2 Answers 2

13

Only the innermost dimension can be omitted. The size of elements in an array are deduced for the type given to the array variable. The type of elements must therefore have a known size.

  • char a[]; has elements (e.g. a[0]) of size 1 (8bit), and has an unknown size.
  • char a[6]; has elements of size 1, and has size 6.
  • char a[][6]; has elements (e.g. a[0], which is an array) of size 6, and has an unknown size.
  • char a[10][6]; has elements of size 6. and has size 60.

Not allowed:

  • char a[10][]; would have 10 elements of unknown size.
  • char a[][]; would have an unknown number of elements of unknown size.

The size of elements is mandatory, the compiler needs it to access elements (through pointer arithmetic).

2
  • 6
    In other words, while the size of the array itself may be unknown, the size of the elements cannot be unknown?
    – vmorph
    Commented Sep 15, 2011 at 15:17
  • Ah, well, thanks for this bit of information. Upon further thought, it only seems logical, as it always does, does it not? ;-)
    – vmorph
    Commented Sep 15, 2011 at 15:27
0

Is this an acceptable work-around?

char * table [] = { "ab", "cd" };

EDIT: Note that it will add an extra '\0' on the end of each string.

1
  • That's a nice solution. But not the answer I was looking for. Still, thanks for showing me a cool trick. :-)
    – vmorph
    Commented Sep 15, 2011 at 15:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.