0

The below given code gives logical error, pls try to give a explanation WHY the given code is not working. Thanks

/*const*/
#include<iostream>
#define n 10
using namespace std;
int main(){
    int i=0, user_val=0, arr[n]={0, 1, 2, 3, 4, 5, 6, 7, 8}, temp=0;
    cout<<"enter the index to add the number"<<endl;
    cin>>user_val;
    for(i=n; i>user_val; i--){
        cout<<"loop"<<i<<endl;
        arr[i+1]=arr[i];
    }
    cout<<"enter the number to add"<<endl;
    cin>>temp;
    arr[i]=temp;
    for(int j=0; j<n; j++){
        cout<<endl<<arr[j];
    }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
T.Y.M.SAI
  • 37
  • 6
  • 2
    How that code _"isn't working "_? [Mcve] as required here please! – πάντα ῥεῖ Nov 28 '21 at 11:18
  • *The below given code gives logical error, pls try to give a explanation WHY the given code is not working.* -- You wrote the code, maybe you would be the best person to answer the question. You certainly didn't write the code by luck, as you must have had some sort of plan in mind before writing it. If the code goes against your plan, then it's your job to debug the code. [What is a debugger?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – PaulMcKenzie Nov 28 '21 at 11:21
  • 2
    `arr[i+1]=arr[i]` If you start at `i=n` you will access your array out of bounds. Maximum allowed index is `n-1`. – Gerhardh Nov 28 '21 at 11:21
  • array indices `10` and `11` are definetly out of bounds for an array of size 10, so the behaviour of the program is undefined. You cannot resize an array, but since you've got 1 element more, you could of course insert an element once, but you need to start shifting the elements to the right by moving index `n-2` to index `n-1`, if necessary. Btw: [`std::copy_backward`](https://en.cppreference.com/w/cpp/algorithm/copy_backward) implements logic that could be used here. – fabian Nov 28 '21 at 11:22

1 Answers1

0

You do

#define n 10
int arr[n];
/* ... */
for(i=n; i>user_val; i--){
    /**/
    arr[i+1]=arr[i];
}

That is a guaranteed access beyond array, even 2 indexes beyond, not only 1.
Accessing the index equal to array size always is.
Because array indexes go 0..(size-1).
Even only arr[i] already would be beyond.

Undefined behaviour, end of explanation.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54