简体   繁体   English

为什么在移动元素后我在索引 arr[2] 处得到 '1' 作为数组的最后一个元素

[英]why am I getting '1' as last element of the array at index arr[2] after shifting the elements

why am I getting '1' as last output at index arr[2] after shifting the elements为什么在移动元素后我在索引 arr[2] 处得到“1”作为最后一个输出

#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输出:2 3 1

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在这里添加 arr[2]=temp

You're indexing an out of bounds array on line您正在在线索引一个越界数组

arr[i] = arr[i + 1]; arr[i] = arr[i + 1];

when i=2 the right hand side evaluates to arr[3], which is out of bounds.i=2时,右侧计算为 arr[3],超出范围。

This generates undefined, buggy behavior.这会产生未定义的错误行为。 This has already been answered much better by people at this question.在这个问题上,人们已经更好地回答了这个问题。

这在 C++ 中被称为未定义行为,您移动的方式是将数组索引到边界之外,这意味着您正在尝试访问数组中不存在的元素。

It depends on what you want the last value to be.这取决于您希望最后一个值是什么。 If you want the array to output 2, 3, 5:如果希望数组输出 2、3、5:

  • store the first element(arr[0]) in a temp variable将第一个元素(arr [0])存储在临时变量中
  • iterate through the array just like you did but stop at the (n-1)th element ie, (i < n-1)像您一样遍历数组,但在第 (n-1) 个元素处停止,即 (i < n-1)
  • then store the temp value in arr[n-1].然后将临时值存储在 arr[n-1] 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM