0

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.

2
  • If the size is 2 elements, then you can have 0, 1. If it is 3 elements, you can have 0, 1, 2. It is zero based indexing. Commented Jul 17, 2016 at 12:23
  • @AndrewTruckle: The answer section is down below! Commented Jul 17, 2016 at 12:29

5 Answers 5

3

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.

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

3 Comments

Array Index starts with 0. So, count[0], count[1], count[2], right?
@AnirudhMurali: Yes, for a grand total of 3, so the type is int[3]. How you declare the array, and how you use it, are two separate things.
Yeah, got it! Sorry for my ignorance :|
2

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.

1 Comment

@LightnessRacesinOrbit: Ya, in this case :)
1

int count[3] = {0};

then

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

2 Comments

I was taught, array index starts with 0. So, count[2] initializes count[0], count[1], count[2]. Right?
@AnirudhMurali: Index is irrelevant when you are declaring. When you declare, you give the length. You should have been taught this also.
0

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

Comments

0

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.

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.