1

Ive got function that shifts array by 1 index to right:

void arrayShiftRight(int array[], int size) {
    int temp = array[size - 1];

    for ( int i = size; i > 0; i-- ) {
        array[i] = array[i - 1];
    }
    array[0] = array[temp];
}

the input is 0 1 2 3 4 5 6

the output is 5 0 1 2 3 4 5

I can't understand why array[temp] becomes 5 instead of 6.

4

1 回答 1

4

您有一个错误,temp不是索引,而是存储值:

// i needs to start at size-1, not at size.
// Otherwise, you'd be writing past the end of the array.
for ( int i = size-1; i > 0; i-- ) {
    array[i] = array[i - 1];
}
array[0] = temp;
于 2013-09-05T13:47:27.453 回答