Онлайн компилятор C

#include <stdio.h> void result(char s[]) { int i = 0; int counter[26] = {0}; int number; while (s[i] != '\0') { if (s[i] >= 'A' && s[i] <= 'Z') { number = s[i] - 'A'; } else if (s[i] >= 'a' && s[i] <= 'z') { number = s[i] - 'a'; } counter[number]++; i++; } int max = 0; for (int j = 0; j < 26; j++) { if (counter[max] < counter[j]) { max = j; } } printf("%c", max + 'a'); } int main() { char a[1001]; scanf("%[^\n]", a); result(a); return 0; }
这段代码的功能是:读取一行字符串,统计其中每个英文字母出现的次数(不区分大小写),然后输出出现次数最多的字母(以小写形式)。如果多个字母出现次数相同,它会输出字母表中靠后的那个(因为比较时用 `counter[max] < counter[j]`,只有严格大于才更新)。

代码中存在一个潜在问题:当字符串中出现非字母字符时,变量 `number` 可能未被赋值,导致数组下标越界。

- 检查 `while` 循环中,如果字符既不是大写也不是小写字母,`number` 就没有被赋值,但后面仍然使用 `counter[number]++`,这会导致访问未初始化的变量,可能造成数组越界或错误计数。
- 考虑在 `else` 分支中处理非字母字符,例如直接跳过(使用 `continue`)或忽略它们,确保只有字母才更新计数器。