A value in my array is getting reassigned and I'm not sure why

I have no idea how the value of time1[0] is getting reassigned when I assign a value to time2[2]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;

void display(int x[2]) {
     if(x[0]<10) {
                    cout << "0";
                    };
     cout << x[0];
     cout << ":";
     if(x[1]<10) {
                    cout << "0";
                    }
     cout << x[1];
     cout << ":";
     if(x[2]<10) {
                    cout << "0";
                    }
     cout << x[2] << endl;
}



int main() {
    int time1[2], time2[2], timeDiff[2];
    
    cout << "Time 1:" << endl;
    cout << "Enter hour: " << endl;
    cin >> time1[0];

    // time1[0] initially assigned

    cout << "Enter minute: " << endl;
    cin >> time1[1];
    cout << "Enter second: " << endl;
    cin >> time1[2];
    cout << endl;
    cout << "Time 2:" << endl;
    cout << "Enter hour: " << endl;
    cin >> time2[0];
    cout << "Enter minute: " << endl;
    cin >> time2[1];

    // time1[0] check. Check is good
    cout << time1[0] << endl;
    
    // this part is changing the value of time1[0] somehow
    cout << "Enter second: " << endl;
    cin >> time2[2];
    cout << endl;
    
    // time1[0] check. Check fails, time1[0] takes on the value of whatever time2[2] is assigned
    cout << time1[0] << endl;


    cout << "Time 1 = ";
    display(time1);
    cout << "Time 2 = ";
    display(time2);
    cout << "Diff   = ";
    
    system("pause");
    return(0);
}
Last edited on
Your arrays are not big enough for the way you are using them.
 
int time1[2]

This is an array of two elements. Valid subscripts are 0 and 1.
1
2
3
4
5
    cin >> time1[0]; // ok

    cin >> time1[1]; // ok

    cin >> time1[2]; // Error - this is outside the array 


To do this you should define the original array with three elements:
 
int time1[3]

halpmepls wrote:
when I assign a value to time2[2]
time2 only has elements from 0 to 1, there is no element 2.
Oh yeah, I feel dumb. thanks guys
Topic archived. No new replies allowed.