Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...