[英]Why is strlen causing a segmentation fault in C?
(警告)是的,这是我正在做的作业的一部分,但是我现在非常绝望,不,我不是在找你们为我解决它,但是任何提示将不胜感激!(/警告)
我正在尝试制作一个交互式菜单,用户应输入一个表达式(例如“ 5 3 +”),并且程序应检测到它的后缀表示法,很遗憾,我遇到了分段错误错误,我怀疑它们与strlen函数的使用有关。
编辑:我能够使其工作,首先
char expression[25] = {NULL};
线
成为char expression[25] = {'\\0'};
并调用时
determine_notation
函数I除去[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
转换为指针:
expr_length = strlen(expression[25]);
// ^^^^
这是问题所在-您的代码引用了数组末尾不存在的元素(未定义的行为),并尝试将其传递给strlen
。
由于strlen
需要一个指向字符串开头的指针,因此调用需要
expr_length = strlen(expression); // Determining size of array input until the NULL terminator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.