Sto*_*oon 0 c c-strings segmentation-fault
(警告)是的,这是我正在处理的任务的一部分,但此时我完全绝望,不,我不是在寻找你们来为我解决它,但任何提示都将不胜感激!(/警告)
我几乎正在尝试制作一个交互式菜单,用户打算输入一个表达式(例如“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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可能收到一条警告,说明您char在此调用中将 a 转换为指针:
expr_length = strlen(expression[25]);
// ^^^^
Run Code Online (Sandbox Code Playgroud)
这就是问题所在 - 您的代码引用了数组末尾之后不存在的元素(未定义的行为)并尝试将其传递给strlen.
由于strlen需要指向字符串开头的指针,因此调用需要
expr_length = strlen(expression); // Determining size of array input until the NULL terminator
Run Code Online (Sandbox Code Playgroud)