Bandrevu Akhil Bandrevu Akhil - 12 days ago 5
C++ Question

Array input after pressing enter becoming 0

#include <iostream>
using namespace std;
int main() {
int start_time[3];
int final_time[3];

int i;
for(i=0;i<3; i++)
cin >> start_time[i];

for(i=0;i<3;i++)
cin >> final_time[i];

int a[10];
for(i=0;i<=10;i++)
a[i]=0;

for(i=0;i<3;i++){
cout << start_time[i] << " " << final_time[i] << endl;
}



}


If I give the following input:

23 53 09
23 53 10


We see that the output is:

23 0
53 53
9 10


Why is it taking the starting input of final_time equal to 0 after I press enter?

How do I solve this?

Answer
    int a[10];
    for(i=0;i<=10;i++)
        a[i]=0;

In this part, you are writing a 0 into a[10]. But a[10] does not exist. a[] only has space for 10 integers, indexed 0 to 9. So you are writing a zero to somewhere in memory, and you overwrote your final_time[0] by chance. Could have been something else or could have crashed your program, too.

Fix this by correcting your loop to for(i=0;i<10;i++) like your other loops.

Writing to an array out of it's allocated bounds is undefined behavior in C++. that basically means it's not defined in the standard and each compiler vendor will have to make something up for their product on what should happen if you do this. So it's rather random and therefor bad (tm). You may get a different behavior when you switch compilers, you may even get a different behavior when you restart your program. In your case, your compiler vendor (like many others) decided that they will just not check if the developer was correct. They just write that zero to the space in memory that a[10] would have been at, had it existed. But it did not. And by plain chance there was another variable at that spot in memory. So that one had it's value overwritten by the zero.

Comments