You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++递归回文判断功能异常 数组长度自动变为14问题求助

问题排查与修复建议

1. 处理后数组长度异常的根因

你定义的lowerPalin是字符数组,C风格字符串要求必须以'\0'作为结束标记,你的代码在筛选完有效字符后没有主动添加结束符,strlen(lowerPalin)会从数组首地址一直往后找内存中随机出现的'\0',才会出现长度异常的问题。
修复方法:筛选字符的for循环结束后,添加一行lowerPalin[x] = '\0';即可。

2. 递归函数存在的问题

你的递归实现缺少终止条件,且初始的high下标设置错误:

  • 初始high值应该是strlen(lowerPalin) - 1,C风格字符串下标从0开始,比如长度为3的字符串最后一个有效字符下标是2,你原来直接用长度作为high,第一次比较就会命中结束符'\0',逻辑完全错误。
  • 递归没有终止条件:当low >= high的时候,说明所有对称位置的字符都已经比对完成,直接返回true即可,否则递归会一直调用直到数组越界,触发未定义行为。

3. 修复后的完整代码

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

bool isPalindrome(char[], int, int);

int main()
{
    char palin[100], lowerPalin[100];

    cout << "Enter a line that might be a palindrome:" << endl;
    cin.get(palin, 100);

    int x = 0;
    for (int i = 0; i < strlen(palin); i++) 
    {
        if((palin[i] != ' ') && (ispunct(palin[i]) == false))
        {
            lowerPalin[x] = tolower(palin[i]);
            x++;
        }
    }
    // 手动添加字符串结束符
    lowerPalin[x] = '\0';

    int low = 0, high = strlen(lowerPalin) - 1; // 修正high初始值

    if (isPalindrome(lowerPalin, low, high))
        cout << "The string is a palindrome." << endl;
    else
        cout << "The string is NOT a palindrome." << endl;

    return 0;
}

bool isPalindrome(char lowerPalin[], int low, int high)
{
    // 递归终止条件:所有对称位置比对完成
    if (low >= high)
        return true;
    if (lowerPalin[low] != lowerPalin[high])
        return false;
    // 符合条件则递归比对下一组对称字符
    return isPalindrome(lowerPalin, low + 1, high - 1);
}

内容的提问来源于stack exchange,提问作者user486543

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:39:01