C++ for loop outputs different results with one array than multiple arrays -
i can't understand why outputs different when put 1 array simple loop , when put 2 arrays it.
int arrr[100]; int arrn[100]; //function run simulation void runsim(){ for(int i=1;i<=100;i++){ arrn[i] = i; arrr[i] = i; } } //function print 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 want, outputs arrn as: 100,1,2,3,4,5,6,...,100 not understand.
if remove arrr loop arrn prints how want
int arrr[100]; int arrn[100]; //function run simulation void runsim(){ for(int i=1;i<=100;i++){ arrn[i] = i; } } //function print 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 0,1,2,3,4,5,6,...,100
interestingly, if change 100's 10's in code problem goes away if keep both arrays in loop.
can me understand i'm missing? i'm sure it's simple because i'm pretty new c++. thank you!
note condition of for
i<=100
, equals sign means access array arrn[100]
, out of bound. undefined behavior, possible. valid range should [0, n)
(n
= 100
), i.e. arrn[0]
, …, arrn[n - 1]
(i.e. arrn[99]
).
you might want change conditions i < 100
.
Comments
Post a Comment