开发者

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

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?


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜