Reputation: 633
I was working on a problem, and tried to initialize an array to 0. Did this, arr[value] = {0}; When I declared an array, it seems to give a different output than what it supposed to give. Here is the code:
Code:
Case 1:
int count[2] = {0};
cout<<count[0];
cout<<count[1];
cout<<count[2];
Gives me output: 001
While, Case 2:
int count[3] = {0};
cout<<count[0];
cout<<count[1];
cout<<count[2];
cout<<count[3];
Gives me output: 0000
Why does this happen? Am I missing something? TIA.
Upvotes: 0
Views: 58
Reputation: 6057
You are going out of bounds! You only allocated memory for two ints and you are accessing third int.
Complier doesn't perform bound checking. It is the job of the programmer.
Array index starts with 0
.
int count[2] = {0};
So you should only access count[0]
and count[1]
that's it. Those are your two valid objects.
Because of this reason you should use vectors
and member function at
which performs bound checking.
Upvotes: 2
Reputation: 385144
C++ is not Visual Basic.
When you declare an array, you must say how many elements it will hold.
When you want three elements, you declare like this:
int array[3];
And use the three elements like this:
array[0]
array[1]
array[2]
You are short-changing yours by one, then attempting to use an array element that does not exist.
Upvotes: 0
Reputation: 847
This happens because int count[2]
defines an array with only two entries so the valid indexes are only 0 and 1 (and not 2).
Upvotes: 0
Reputation: 17668
int count[3] = {0};
then
cout<<count[3]; // <-- out-of-bound array access yields undefined behaviour
Upvotes: 1
Reputation: 92241
Your index is out of range. In int count[2]
the 2
says that there a 2 members, but you try to display 3 members. The result of that is undefined.
Upvotes: 3