为什么strlen在C中导致分段错误?
(警告)是的,这是我正在做的任务的一部分,但在这一点上我完全绝望,不,我不是在寻找你们为我解决它,但任何暗示都将非常感激! /警告)为什么strlen在C中导致分段错误?
我非常想做一个交互式菜单,用户是为了输入一个表达式(例如“5 3 +”),程序应该检测到它在后缀表示法中,不幸的是我已经得到分段错误错误,我怀疑它们与使用函数的功能有关。
编辑:我能够使它发挥作用,首先
char expression[25] = {NULL};
线
成为char expression[25] = {'\0'};
并调用
determine_notation
功能,当我删除该数组中的[25]
我路过像这样:determine_notation(expression, expr_length);
另外
input[length]
第I部分改为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
我明白了,这已经解决了我的问题的一部分。至少现在它实际上是输入功能。万分感谢! – Stoon
'输入[长度]''是'\ 0''(和:''输入[长度-1 ]'是''\ n''并且:'expression [25];索引超出对象的大小) – wildplasser
strlen获取一个字符串(指向第一个字符),而不是一个字符。 –
'char expression [25] = {NULL};'没有感觉。用'{'\ 0'}'或''''替换为' – Stargateur