Joe Jacksson Joe Jacksson - 4 months ago 10
C++ Question

C++ - How do you create multidimensional arrays?

I'm new to C++. I'm trying to create a multidimensional array. What's wrong with this code?

int sorted_array[] = {{2, 3}, 5, 7};


It's giving me this error.

error: braces around scalar initializer for type 'int'


Thanks.

Answer

When declaring multidimensional arrays, all the dimensions except the first one must be specified.

e.g.

int sorted_array[][2] = {{2, 3}, {5}, {7}};

which is equivalent to :

int sorted_array[3][2] = {{2, 3}, {5}, {7}};

You cannot use:

int sorted_array[][] = {{2, 3}, {5}, {7}};

and expect the compiler to deduce 2 for the second dimension.

Comments