Anirudh Murali
Anirudh Murali

Reputation: 633

Empty Initialization of Array varied output

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

Case 1 Case 2

Why does this happen? Am I missing something? TIA.

Upvotes: 0

Views: 58

Answers (5)

ani627
ani627

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

Lightness Races in Orbit
Lightness Races in Orbit

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

s7amuser
s7amuser

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

tdao
tdao

Reputation: 17668

int count[3] = {0};

then

cout<<count[3]; // <-- out-of-bound array access yields undefined behaviour

Upvotes: 1

Bo Persson
Bo Persson

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

Related Questions