Array Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Array Question

What is the output of this code? int arr[3] = {1,3}; cout << arr[2]; Got this question in a challenge. Apparently the correct answer is 0 (instead of error or 3)... I thought that the question was weird... 1) How can there be only be two members in the array when the index within the first square brackets is 3? 2) How do we make sense of printing an index-specified, non-existing value of a non-existing curly brackets-bound member? Is it not impossible to print arr[2] despite that there are only two members within the curly brackets?

18th Jul 2020, 8:49 AM
Solus
Solus - avatar
2 Answers
+ 2
The answer is 0. The initializer has less elements than the size of the array, in which case the unspecified elements will be set to 0. Try it in the playground or any compiler if in doubt. Try this: int arr[10] = { 12, 34 }; and if you print all the elements, you'll see that only the first two have been initialized to 12 and 34, the rest are 0.
18th Jul 2020, 11:11 AM
lion
lion - avatar
+ 1
It's a poorly designed question. Accessing an array member outside its size will lead to memory leak, returning junk values. Please report that question so that it can be removed.
18th Jul 2020, 8:55 AM
Gordon
Gordon - avatar