0

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!

2
  • 4
    for(int i=1;i<=100;i++) ... problem already: arrays are zero-based in C++. You are trying to access a region of memory which should not be accessible. Commented Aug 29, 2016 at 1:57
  • there's no x[100] for you to access Commented Aug 29, 2016 at 2:21

2 Answers 2

4

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.

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

1 Comment

Wow thank you! I knew it was going to be something simple.
2

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

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.