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.
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.
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.
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".
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.