Reputation: 9
I can't understand why the outputs are different when I put 1 array into a very simple for loop and when I put two arrays into it.
int arrR[100];
int arrN[100];
//function to run the simulation
void runsim(){
for(int i=1;i<=100;i++){
arrN[i] = i;
arrR[i] = i;
}
}
//function to print the array
void printarr(int x[100]){
for(int i=0;i <= 100;i++){
cout << x[i] << ", ";
}
cout << endl;
}
int main(){
runsim();
printarr(arrR);
printarr(arrN);
return 0;
}
This outputs arrR as: 0,1,2,3,4,5,6,...,100 which is what I want, but it outputs arrN as: 100,1,2,3,4,5,6,...,100 which I do not understand.
If I remove arrR from the for loop arrN prints how I want
int arrR[100];
int arrN[100];
//function to run the simulation
void runsim(){
for(int i=1;i<=100;i++){
arrN[i] = i;
}
}
//function to print the array
void printarr(int x[100]){
for(int i=0;i <= 100;i++){
cout << x[i] << ", ";
}
cout << endl;
}
int main(){
runsim();
printarr(arrN);
return 0;
}
This outputs arrN as 0,1,2,3,4,5,6,...,100
Interestingly, if I change all the 100's to 10's in the code this problem also goes away even if I keep both arrays in the for loop.
Can anyone help me understand what I'm missing? I'm sure it's simple because I'm pretty new to C++. Thank you!
Upvotes: 0
Views: 70
Reputation: 9888
Please note that array indexing start from 0
instead of 1
ends at n-1
instead of n
. Now in your function runsim()
you are accessing the assigning value 100
to arrN[100]
and arrR[100]
which is not possible leads to undefined behavior.
You should change the for loop condition
for(int i = 0; i < 100; i++) {
// Do something.
}
Please note that accessing element out bound will not produce any error as well. For more detail please refer Accessing an array out of bounds gives no error
Upvotes: 2
Reputation: 172884
Note the condition of for
is i<=100
, equals sign means you will access the array by arrN[100]
, then get out of the bound. This is undefined behavior, anything is possible. The valid range should be [0, N)
(N
= 100
), i.e. arrN[0]
, …, arrN[N - 1]
(i.e. arrN[99]
).
You might want to change all the conditions to i < 100
.
Upvotes: 4