gpt4 book ai didi

c - 是什么导致此函数中出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:06 24 4
gpt4 key购买 nike

<分区>

因此,作为练习,我正在开发一个使用递归函数的代码,以制作一个简单的数学表达式计算器。问题是,当我运行它时出现段错误 (6) 或 (11),但我已经检查了一百次,并且每个函数调用似乎只从它上面的函数中的变量访问内存堆栈,由指针 *init 提供。我哪里弄错了?

代码如下:

int solve(char *expression, int *init) {

int result;
int l = strlen(expression);
int i = *init;

//Inicializing result:
for (int n = 0; n <= l; n++) {
if ((expression[n]=='1')||(expression[n]=='2')||(expression[n]=='3')||(expression[n]=='4')||(expression[n]=='5')||
(expression[n]=='6')||(expression[n]=='7')||(expression[n]=='8')||(expression[n]=='9')) {
result = expression[n]-48;
break;
}
}

//Doing calculations:
int j = i;
for (j; j <= l; j++) {
if (expression[j] == '(') {
result = result + solve(expression, &j);
}
if (expression[j] == '+')
result = result + (expression[j+1]-48);
if (expression[j] == '-')
result = result - (expression[j+1]-48);
if (expression[j] == '*')
result = result * (expression[j+1]-48);
if (expression[j] == '/')
result = result / (expression[j+1]-48);
if (expression[j] == ')')
return result;
}
return result;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com