c - 以下 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 函数中,但我找不到它。
解决方案
而不是
char* expression = "";
做
char[MAX_expression_length+1] expression;
或在 append 函数中使用 realloc
推荐阅读
- node.js - Set-cookie Header 不会为浏览器设置 cookie
- ubuntu - 在 mat4.h 中使用默认构造函数后,联合使 gcc 抛出错误,在 mat4.cpp 中创建错误,就像没有减速匹配 mat4::mat4
- node.js - Heroku 错误 - ENOENT:没有这样的文件或目录,scandir '/app/server'
- c# - 我怎样才能按时间而不是按位置来处理vector3?
- python - 生产环境中文件中的 Django 日志错误和回溯
- python-3.x - 在没有错误的python中使用类和对象时遇到困难
- android-studio - 我想在我的 android studio 应用程序中播放 youtube 视频,并在视频中播放 youtube 提供的广告
- javascript - onCaptureCheckout 不是函数?
- javascript - 使用代理时 PDF.JS 窗口和文档元素的名称更改(Javascript)
- python - 如何创建一个文件夹来存储来自网站抓取的图像