C arrayShiftRight()函数中存在错误
我得到了将数组向右移动1个索引的函数:C arrayShiftRight()函数中存在错误,c,arrays,sorting,C,Arrays,Sorting,我得到了将数组向右移动1个索引的函数: 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]; } 输入是 01 2 3 4 5 6 输出是 50123445 我不明白为什么数组
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];
}
输入是
01 2 3 4 5 6
输出是
50123445
我不明白为什么数组[temp]变为5而不是6。您有一个off by one错误,
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;
您有一个off by one错误,
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;
你是对的,数组[temp]值是6,然后改成了5,现在我看到了我的错误,thanx很多。你是对的,数组[temp]值是6,然后改成了5,现在我看到了我的错误,thanx很多。