-2

If I have an array with 3 members, printing the third element outputs 0, I wanna know why is that

    int A[3] = {1 , 2, 3};
    cout << A[3];

it outputs this

0

Thanks.

  • 3
    The only valid indices are 0, 1, and 2, when the array is of size 3. – cigien Jul 19 '20 at 18:43
  • FYI, both GCC and Clang [warn about this](https://gcc.godbolt.org/z/jY7GM1). That should give a clue that it's not valid. – chris Jul 19 '20 at 18:47
  • Had you seen a value like 8347534, if would have made perfect sense to you. But 0 is no less different than any other number. Its no more valid on an out of bound access than 8347534. – StoryTeller - Unslander Monica Jul 19 '20 at 18:51
  • 2
    Welcome to Stack Overflow! Your question was closed because it's very similar to others that have been asked in the past. Hopefully that won't put you off posting other questions in future, but remember to search first and try to only ask a question of you think it hasn't been asked before. – Arthur Tacca Jul 19 '20 at 19:03

3 Answers3

2

Array indices start at 0. The third entry is A[2].

Your code is accessing outside the bounds of the array and has undefined behaviour. Thus, any result is acceptable.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

C++ uses zero based indexing, so the first element is A[0], the second element is A[1], and the third element is A[2]. Try printing them out in your program and you'll see that. So A[3] isn't the third element, as you said... It's actually the fourth! Since your array only has three elements, trying to access this can return anything, and it just happened to return zero by chance. It can actually do anything, like crash your program or even weirder ... This is called "undefined behaviour".

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
0

Indexing in C++ begins at the 0, so you last element has the index 2. Accessing the third element in the array is called "out of bound access" and is undefined behaviour, you could have gotten any number. In your case, the memory location after the last element happened to contain 0, but it must not.

DKolter
  • 21
  • 3