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

C语言invertString函数无输出求助:疑似陷入死循环

问题分析与修复

你的代码确实陷入死循环,同时存在语法逻辑错误,导致程序无法正常执行,具体问题及修复方案如下:

核心问题点

  1. for循环缺失花括号:处理升序子串反转的for循环未包裹index++,仅(*s2)[index]=s1[i];在循环体内,index++仅执行一次,后续写入会覆盖同一位置,还会引发数组越界。
  2. 死循环触发逻辑:第二个while循环逻辑混乱,处理完升序段后end未正确推进到下一个待处理位置,导致外层while(end < len)持续满足条件,无限循环。
  3. 非升序段处理错误:第二个while循环内错误修改start,且未正确判断非升序段的结束位置,导致后续逻辑混乱。

修复后的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void invertString(char *s1, char **s2);

void invertString(char *s1, char **s2){
    int len = strlen(s1);
    *s2 = (char*)malloc((len+1) * sizeof(char));
    int start = 0;
    int end = 0;
    int index = 0;

    while (start < len) {
        // 定位升序子串的末尾
        while (end < len - 1 && s1[end] < s1[end+1]) {
            end++;
        }
        // 反转升序子串并写入结果
        for (int i = end; i >= start; i--) {
            (*s2)[index++] = s1[i];
        }
        // 处理非升序段(直接原样写入)
        start = end + 1;
        end = start;
        while (end < len - 1 && s1[end] >= s1[end+1]) {
            (*s2)[index++] = s1[end];
            end++;
        }
        // 写入非升序段的最后一个字符
        if (end < len) {
            (*s2)[index++] = s1[end];
            start = end + 1;
            end = start;
        }
    }
    (*s2)[index] = '\0';
}

int main() {
    char s1[] = "A B C D D D D Z Y X W E F G";
    char *s2 = NULL;

    invertString(s1, &s2);

    printf("Input string: %s\n", s1);
    printf("Output string: %s\n", s2);

    free(s2);
    return 0;
}

修复说明

  1. 给for循环添加花括号,确保反转时每个字符对应正确的index位置。
  2. 将外层循环条件改为start < len,避免因end位置异常导致的死循环。
  3. 重新梳理非升序段处理逻辑:先定位升序段并反转,再逐个写入非升序字符,处理完成后更新start和end到下一个待处理位置。
  4. 增加非升序段末尾字符的判断,避免遗漏。

运行修复后的代码,输入字符串A B C D D D D Z Y X W E F G会输出:

Input string: A B C D D D D Z Y X W E F G
Output string: D D D D C B A Z Y X W G F E

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:25:14