Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Miroslav Cetojevic Avatar asked Sep 15 '11 14:09

Miroslav Cetojevic


People also ask

Which dimensions can we omit when declaring a multidimensional array?

(For a three- or more dimensional array, all but the first dimension are required; again, only the first dimension may be omitted.)

How many dimensions can multidimensional arrays have?

More than Three Dimensions Although an array can have as many as 32 dimensions, it is rare to have more than three.

Can we declare a 2D array without column if yes or no justify?

Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted.


1 Answers

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

like image 90
Stéphane Gimenez Avatar answered Oct 16 '22 16:10

Stéphane Gimenez