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

C语言编写字符数组去空格函数遇空格后停止复制的问题求解

问题根因

你代码的核心问题是遍历原字符串的索引和写入新字符串的索引用了同一个变量,具体触发逻辑如下:

  • 测试用例"hello world"中,空格位于原字符串索引5的位置
  • 程序遇到空格时会把遍历索引i自增到6,直接给str[6]赋值字符w,中间str[5]的位置从未被写入内容
  • 你调用malloc申请的内存未初始化,str[5]位置恰好是\0(字符串结束符),调用printf输出字符串时遇到\0就会终止,因此只能输出空格前的hello

除此之外还存在多个潜在问题:

  • 遍历原字符串的while循环没有做边界判断,如果原字符串末尾是空格,会出现数组越界访问
  • 新生成的字符串末尾没有手动补\0结束符,会导致输出乱码
  • 函数内给形参str重新申请内存不会影响外部传入的指针,且所有malloc申请的内存都没有释放,存在内存泄漏
  • main函数的定义不符合C标准规范
修正后的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeSpace(char *str) {
    int len = strlen(str);
    char *new_str = malloc((len + 1) * sizeof(char)); // 刚好存原串长度+结束符,避免内存浪费
    int write_idx = 0; // 单独维护新字符串的写入索引

    for (int read_idx = 0; read_idx < len; read_idx++) {
        if (str[read_idx] == ' ') {
            continue; // 跳过空格,不写入新串
        }
        new_str[write_idx++] = str[read_idx];
    }
    new_str[write_idx] = '\0'; // 手动补充字符串结束符

    printf("处理后的字符串: %s\n", new_str);
    free(new_str); // 释放申请的堆内存,避免泄漏
}

int main() {
    char *test = malloc(1000 * sizeof(char));
    strcpy(test, "hello world");
    removeSpace(test);
    free(test); // 释放main函数内申请的内存
    return 0;
}
验证输出
处理后的字符串: helloworld

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:06:05