首页 > 解决方案 > 以下 C 代码输出分段错误错误,我几乎无法理解为什么

问题描述

#include <stdio.h>

void append(char* s, char n);
void splitstr(char* string);

int main()
{
    splitstr("COMPUTE 1-1");
    printf("\n");
    splitstr("COMPUTE 1+1");
    printf("\n");
    splitstr("COMPUTE 1*1");
    return 0;
}

void append(char* s, char ch) {
    while(*s != '\0'){
        s = s + 1;
    }
    *s = ch;
    s = s + 1;
    *s = '\0';
}

void splitstr(char* string){
    int count = 1;
    char* expression = "";
    while(*string != '\0'){
        if(count > 8){
            append(expression, *string);
            string = string + 1;
            count = count + 1;
        }else{
            string = string + 1;
            count = count + 1;
        }
    }
    printf("%s",expression);
}

输入和输出示例:
输入:COMPUTE 1+1
输出:1+1
输入:COMPUTE 2-6
输出:2-6

最初,此代码不包含 stdio.h(我这样做是为了在在线 C 编译器上进行测试),因为我正在从头开始构建操作系统,所以我需要自己编写所有函数。我认为问题可能出在 append 函数中,但我找不到它。

标签: c

解决方案


而不是 char* expression = "";char[MAX_expression_length+1] expression;

或在 append 函数中使用 realloc


推荐阅读