C++数组右移功能实现错误排查:代码问题分析
Fixing Your Array Right Shift Issue
Hey there! Let's break down why your array right shift isn't producing the correct output, and how to fix it.
The Problem with Your Current Code
Looking at your shift loop:
for(int i=8; i>0; i--) { arrays[i]=arrays[i-k]; }
You've got three critical issues here:
- Array Index Out of Bounds: C++ arrays are 0-indexed, so your
arraysonly has valid indices from0to7. Wheni=8, you're writing to memory outside the array—this causes undefined behavior (like the random0you're seeing). - Invalid Negative Indices: When
i <= k,i-kbecomes negative (e.g., whenk=3andi=2,i-k=-1). Reading from negative indices is illegal and pulls garbage values into your array. - Data Loss: You're overwriting elements before saving the original values of the last
kelements, so those values get lost instead of moving to the front.
The Correct Approach for Right Shift
To right shift an array by k positions (with the last k elements wrapping to the front), follow these steps:
- Save the last
kelements of the array to a temporary storage. - Shift the first
8 - kelements of the array to the right bykpositions (start from the end to avoid overwriting data you still need). - Copy the saved
kelements into the firstkpositions of the array.
Fixed Code
Here's the corrected version of your code with explanations:
#include<iostream> using namespace std; int main() { int arrays[8]; int k; // Input 8 integers cout << "Enter Values for an Array of size 8" << endl; for(int i=0; i<8; i++) { cin >> arrays[i]; } // Print original array cout << "You Entered Numbers are: [ "; for(int i=0; i<8; i++) { cout << arrays[i] << " "; } cout << "]\n"; // Get shift count cout << "Enter the Number of Shift: "; cin >> k; // Handle cases where k >=8 (optional but robust) k = k % 8; if(k == 0) { // No shift needed cout << "Shifted Array: [ "; for(int i=0; i<8; i++) { cout << arrays[i] << " "; } cout << "]\n"; return 0; } // Step 1: Save last k elements int temp[k]; for(int i=0; i<k; i++) { temp[i] = arrays[8 - k + i]; } // Step 2: Shift first 8-k elements right by k positions for(int i=7; i >= k; i--) { arrays[i] = arrays[i - k]; } // Step 3: Copy temp elements to the front for(int i=0; i<k; i++) { arrays[i] = temp[i]; } // Print shifted array cout << "Shifted Array: [ "; for(int i=0; i<8; i++) { cout << arrays[i] << " "; } cout << "]\n"; return 0; }
Key Fixes Explained
- Temporary Storage: We use a
temparray to hold the lastkelements so they don't get overwritten when shifting the rest of the array. - Safe Shifting: By iterating from the end of the array (
i=7) backwards tok, we ensure we don't overwrite elements that haven't been shifted yet. - Robustness: Adding
k = k % 8handles cases where the user enters a shift count larger than 8 (since shifting 8 positions is the same as shifting 0).
Testing this with k=3 and the input 1 2 3 4 5 6 7 8 will give you the correct output: [ 6 7 8 1 2 3 4 5 ].
内容的提问来源于stack exchange,提问作者Alaa KM
相关产品推荐
相关产品推荐

