0

Why does brace-enclosed initialization not work for this integer array?

#include <iostream>
int main()
{
    int arr[2] = {0};
    for (int i = 0; i <= 2; i++)
        std::cout << arr[i] << " ";
}

The output is 0 0 -731153664. Why isn't it 0 0 0?

1
  • 1
    Because an array of X elements have indexes from 0 to X - 1. The size of the array is the number of elements, not the top index. Something which any book, tutorial or class should have mentioned. Commented Apr 9, 2020 at 5:01

1 Answer 1

1

Because there's only two elements in the array

for (int i = 0; i < 2; i++)

Printing arr[2] is undefined behaviour

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.