使用tmp实现rotateArray数组旋转函数的C语言代码问题排查及修正求助
Let’s break down the issues in your initial code and walk through how you landed on the working solution:
1. First Version: Critical Breaking Issues
Your first attempt had two showstopper problems that caused blank output:
- Wrong function usage: You tried to pass
arr[i](a single integer element) torotateArray, which expects an array pointer. On top of that,rotateArraywas declared to return anintbut had noreturnstatement—this triggers undefined behavior, which can lead to random output or crashes. - Invalid array declaration:
int size,i,arr[i];creates a variable-length array (VLA) using an uninitializedi(which holds a garbage value). This means your array’s size is random, leading to memory corruption or failed input/output operations.
2. Second Version: Partial Fix, Persistent Size Issue
When you switched rotateArray to void (the right call, since we’re modifying the array in-place instead of returning a value), you still kept the array declaration int arr[i]; before reading size. Since i is uninitialized here, the array’s size isn’t tied to the user’s input—it only worked when you hardcoded i to 10 because that matched your test input, but it breaks for any other size.
3. The Correct Fix: Declare VLA After Getting Valid Size
The key fix was moving int arr[size]; after you read size from the user. In C, variable-length arrays require their size to be a known, valid integer at the time of declaration. By declaring the array after scanf("%d",&size);, you ensure the array is exactly the size the user requested, eliminating memory access errors.
Final Working Code (With a Minor Best Practice Fix)
#include <stdio.h> // Declare the function before main for compiler clarity void rotateArray(int arr[], int size); int main() { int size,i; printf("Enter N: "); scanf("%d",&size); int arr[size]; // VLA declared with a known, valid size for(i=0;i<size;i++) { scanf("%d",&arr[i]); } rotateArray(arr,size); // Pass the array pointer, not a single element for(i=0;i<size;i++) { printf("%d ",arr[i]); } } void rotateArray(int arr[], int size) { int i, tmp; tmp = arr[0]; // Shift all elements left by one for(i=1;i<size;i++) { arr[i-1] = arr[i]; } // Place the original first element at the end (fixed from your first version's loop placement) arr[size-1] = tmp; }
Also, a quick note: in your first rotateArray implementation, you set arr[size-1] = tmp; inside the loop—this would overwrite the last element every iteration, which is incorrect. Moving it outside the loop (like you did in your final code) ensures we only place the original first element at the end once all shifts are complete.
内容的提问来源于stack exchange,提问作者WWoPPoWW

