Multi-dimensional array initialization

user4920379

I have seen a question in C++ exam today:

Given the array int Multi[2][3][2] = {14,11,13,10,9,6,8,7,1,5,4,2}, what is the value of Multi[1][1][0]?

Shouldn't 3-dimensional arrays be initialized like this: {{{},{}},{{},{}},{{},{}}}? How can I find the value of element with such indeces? It's so confusing.

gdrt

You can initialize arrays in both ways, though the usage of curly inner braces is recommended as it improves the readability.

The easiest way to find the value of an element of a multi-dimensional array non-formatted with braces is by splitting the array. For example, your array's dimensions are 2x3x2:

First split the array into 2 sets (2x3x2)

{14,11,13,10,9,6,8,7,1,5,4,2} --> {{14,11,13,10,9,6}, {8,7,1,5,4,2}}

Then split each set into 3 sets (2x3x2)

{{14,11,13,10,9,6},{8,7,1,5,4,2}} --> {{{14,11}, {13,10} ,{9,6}}, {{8,7}, {1,5}, {4,2}}}

Now, as you see there are 2 elements left in every smaller set (2x3x2), so you have formatted your array with braces.

Now it's simpler to find the value of the element with the index of [1][1][0]. This element is the 2nd ([1][1][0]) bigger set's 2nd ([1][1][0]) smaller set's 1st ([1][1][0]) element, so the answer is 1.


That being said, such an exam question shows the lack of professionalism of your teacher, who's more interested in abusing the programming language syntax, rather than teaching fundamental initialization rules.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related