2

I get error in compilation with the following definition.

int  matrix[ ][ ] = { { 1, 2, 3}, {4,5,6} };

char str[ ][ ] = { "abc", "fgh" };

Why is the compiler complaining missing subscript and too many initializers.

kennytm
  • 491,404
  • 99
  • 1,053
  • 989
rpoplai
  • 21
  • 1
  • 3

4 Answers4

8

When you declare a multi-dimensional array, you must explicitly define the size of all but the last dimension. Otherwise, the compiler won't know how to find a given value in the array.

edit: read my post here

Community
  • 1
  • 1
Kricket
  • 3,879
  • 7
  • 31
  • 44
6

If an array is defined as int arr[ ROWS ][ COLS ]; then any array notation arr[ i ][ j ] can be translated to pointer notation as

*( arr + i * COLS + j )

Observe that the expression requires only COLS, it does not require ROWS. So, the array definition can be written equivalently as

int arr [][ COLS ];

But, missing the second dimension is not acceptable.

Further understanding can be achieved by following the three examples given below. In all three examples, the same array notation arr[ 2 ][ 3 ] is translated to pointer notation.

  • Between A and B, ROWS is same but COLS is different; result = pointer notation is different.

  • Between A and C, ROWS is different but COLS is same; result = pointer notation is same.

Examples:

A. int arr[ 4 ][ 7 ];      arr[2][3] = arr + 2 * 7 + 3 = arr + 17
B. int arr[ 4 ][ 5 ];      arr[2][3] = arr + 2 * 5 + 3 = arr + 13
C. int arr[ 6 ][ 7 ];      arr[2][3] = arr + 2 * 7 + 3 = arr + 17
Arun
  • 19,002
  • 9
  • 48
  • 59
0

Try

include <string>

and

string str[] = { "abc", "fgh" };
Julio Santos
  • 3,769
  • 1
  • 25
  • 47
0

int matrix[2][3] = { { 1, 2, 3}, {4,5,6} };
char str[2][4] = { "abc", "fgh" };

the first declaration will make 2d int array has 2 rows with 3 col.
the second will make 2d char array with 2 rows and 4 col. the 4th element in each row in the char array is the NULL char

Aboelnour
  • 1,373
  • 3
  • 14
  • 38