(警告)是的,这是我正在做的作业的一部分,但是我现在非常绝望,不,我不是在找你们为我解决问题,但是任何提示将不胜感激!(/警告)
我正在尝试制作一个交互式菜单,用户应输入一个表达式(例如“ 5 3 +”),并且程序应检测到它的后缀表示法,很遗憾,我遇到了分段错误错误,我怀疑它们与strlen函数的使用有关。
编辑:我能够使其工作,首先该
char expression[25] = {NULL};
行
成为char expression[25] = {'\0'};
当调用
determine_notation
函数时,我[25]
从数组中删除了,就像这样:determine_notation(expression, expr_length);
就像之前的评论中提到的那样,
input[length]
我更改后的部分也是如此。input[length-2]
input[length] == '\0'
input[length--] == '\n'
总而言之,感谢您的帮助!
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int determine_notation(char input[25], int length);
int main(void)
{
char expression[25] = {NULL}; // Initializing character array to NULL
int notation;
int expr_length;
printf("Please enter your expression to detect and convert it's notation: ");
fgets( expression, 25, stdin );
expr_length = strlen(expression[25]); // Determining size of array input until the NULL terminator
notation = determine_notation( expression[25], expr_length );
printf("%d\n", notation);
}
int determine_notation(char input[25], int length) // Determines notation
{
if(isdigit(input[0]) == 0)
{
printf("This is a prefix expression\n");
return 0;
}
else if(isdigit(input[length]) == 0)
{
printf("This is a postfix expression\n");
return 1;
}
else
{
printf("This is an infix expression\n");
return 2;
}
}
您可能会收到警告,说明您char
在此调用中将a转换为指针:
expr_length = strlen(expression[25]);
// ^^^^
这就是问题所在-您的代码引用了数组末尾不存在的元素(未定义的行为),并尝试将其传递给strlen
。
由于strlen
采用指向字符串开头的指针,因此调用需要
expr_length = strlen(expression); // Determining size of array input until the NULL terminator
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句