The problem is that newposition = i - shiftSteps + 10;
results in a negative value for shiftSteps == 15
and i < 5
. This results in an out-of-bounds access.
You need to ensure that the rotation amount is below the number of elements of the array, which can be achieved with a modulus operator.
shiftSteps = shiftSteps % 10;
for (int i = 9; i >= 0; i--)
{
newposition = i - shiftSteps;
if (newposition < 0)
newposition += 10;
numbers[newposition] = numberscopy[i];
}
This will work for non-negative values of shiftSteps
. If you also need to handle negatives, you should adjust the condition in the loop accordingly.
PS: Also, note that in your code shiftSteps
is left uninitialized.
PPS: You could also use std::rotate
algorithm.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…