在线编译器 C

#include <stdio.h> #include <string.h> int main() { long long int k; char a[1001],b[1001]; scanf("%lld", &k); scanf("%[^\n]", a); int lon = strlen(a); if(k > lon) { k = k % lon; } for(int i = 0; i< lon -k; i++) { b[i+lon + 1] = a[i]; } int j = 0; for(int i = lon - k; i< lon; i++) { b[j] = a[i]; j++; } for(int i = 0; i < lon; i++) { printf("%c", b[i]); } return 0; }
This code attempts to rotate a string to the left by `k` positions. It reads a number `k` and a line of text, then tries to rearrange the characters. The main idea is to split the string into two parts and swap their order.

- The first loop copies the first part of the string (from index 0 to `lon - k - 1`) into array `b`, but it writes to positions starting at `i + lon + 1`, which is far beyond the valid range of `b`. This will cause undefined behavior because `b` only has space for 1001 characters.
- The second loop copies the last `k` characters to the beginning of `b`, which is correct in logic, but the first loop has already corrupted the array or written outside it.

Check the index calculation in the first loop. You want to place the first part of the string after the last `k` characters in `b`, not at an offset larger than the array size.