Home > OS >  why am I getting '1' as last element of the array at index arr[2] after shifting the eleme
why am I getting '1' as last element of the array at index arr[2] after shifting the eleme

Time:07-07

why am I getting '1' as last output at index arr[2] after shifting the elements

#include <iostream>
using namespace std;

void shifting(int* arr)
{
    int i, j;
    for (i = 0; i < 3; i  )
    {
        arr[i] = arr[i   1];
    }

    for (i = 0; i < 3; i  )
    {
        cout << arr[i] << endl;
    }
}

int main()
{
    int array[n] = { 5, 2, 3 };
    shifting(array);       //shifting the elements to left side 
    return 0;
}

output: 2 3 1

CodePudding user response:

The way you are shifting is wrong. The proper way to do it is to store the value in a temp element and then shift.

For eg.

temp=arr[0]
for (i = 0; i < 3; i  )
    {
        arr[i] = arr[i   1];
    }

Here add arr[2]=temp

CodePudding user response:

You're indexing an out of bounds array on line

arr[i] = arr[i 1];

when i=2 the right hand side evaluates to arr[3], which is out of bounds.

This generates undefined, buggy behavior. This has already been answered much better by people at this question.

CodePudding user response:

This is called undefined behavior in C , the way you are shifting is indexing the array out of bounds, meaning that you are trying to access an element that doesn't exist in the array.

CodePudding user response:

It depends on what you want the last value to be. If you want the array to output 2, 3, 5:

  • store the first element(arr[0]) in a temp variable
  • iterate through the array just like you did but stop at the (n-1)th element i.e., (i < n-1)
  • then store the temp value in arr[n-1].
  • Related