Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...