C语言字符串字符频率统计代码异常问题求助
问题排查:字符频率统计函数输出异常
核心错误分析
未初始化的频率数组
局部数组charsFrequencies声明时未初始化,内存中存储的是随机垃圾值。你使用charsFrequencies[i] += charCount;进行累加操作,相当于把随机值和统计出的真实次数相加,导致输出异常。输入"bb"时结果正常只是巧合——此时数组对应的垃圾值恰好为0。错误的数组终止操作
charsFrequencies是int类型数组,给它赋值'\0'(ASCII值0)完全没有必要,且当differentCharsNumber等于stringlength时,charsFrequencies[differentCharsNumber]会触发数组越界访问。
修正步骤
- 声明
charsFrequencies时直接初始化为0:int charsFrequencies[stringlength] = {0}; - 将统计频率的语句从累加改为直接赋值:
charsFrequencies[i] = charCount; - 移除
charsFrequencies[differentCharsNumber] = '\0';这行无意义代码 - (可选优化)把
j = i;替换为break;,让循环退出逻辑更清晰 - (可选优化)内层判断字符是否存在的循环,将
j < i改为j < differentCharsNumber——因为chars数组仅存储了differentCharsNumber个不同字符,可减少无效循环次数
修正后的完整代码
void printCharactersFrequenciesOf(char s[]){ size_t stringlength = strlen(s); // 获取字符串长度 char chars[stringlength]; // 存储不同字符的数组 // 初始化频率数组为0,避免垃圾值干扰 int charsFrequencies[stringlength] = {0}, charAlreadyExists, differentCharsNumber = 0; // 提取字符串中的不同字符 for (int i = 0; i < stringlength; i++){ charAlreadyExists = 0; // 仅遍历已存储的不同字符,优化循环范围 for (int j = 0; j < differentCharsNumber; j++){ if (s[i] == chars[j]){ charAlreadyExists = 1; break; // 直接终止循环,替代j=i的写法 } } if (charAlreadyExists == 0){ chars[differentCharsNumber] = s[i]; differentCharsNumber++; } } int charCount; // 统计每个不同字符的出现频率 for (int i = 0; i < differentCharsNumber; i++){ charCount = 0; for (int j = 0; j < stringlength; j++){ if (chars[i] == s[j]){ charCount++; } } charsFrequencies[i] = charCount; // 直接赋值统计结果 } // 输出每个字符的频率 for (int i = 0; i < differentCharsNumber; i++){ printf("Frequency of '%c': %d\n", chars[i], charsFrequencies[i]); } }
内容的提问来源于stack exchange,提问作者Thriller
相关产品推荐
相关产品推荐

