(警告)是的,這是我正在做的任務的一部分,但在這一點上我完全絕望,不,我不是在尋找你們爲我解決它,但任何暗示都將非常感激! /警告)爲什麼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;
}
}
'輸入[長度]''是'\ 0''(和:''輸入[長度-1 ]'是''\ n''並且:'expression [25];索引超出對象的大小) – wildplasser
strlen獲取一個字符串(指向第一個字符),而不是一個字符。 –
'char expression [25] = {NULL};'沒有感覺。用'{'\ 0'}'或''''替換爲' – Stargateur