(警告)はい、これは私が取り組んでいる課題の一部ですが、私は完全にこの時点で絶望的でありません。あなたは私のためにそれを解決する人を探しているわけではありませんが、 /警告)strlenがCでセグメンテーション違反を引き起こすのはなぜですか?
私はかなりインタラクティブなメニューを作ろうとしていますが、ユーザは式(例えば "5 3 +")を入力する必要があり、プログラムはそれが後置記表記であることを検出するはずです。セグメンテーションフォールトエラーが発生し、strlen機能の使用と関係があると思われます。 determine_notation(expression, expr_length);
編集:私はそうのように渡しています配列から
[25]
を削除determine_notation
関数を呼び出すときに、私はそれを動作させることができた、最初のchar expression[25] = {NULL};
ライン
はchar expression[25] = {'\0'};
なり、
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;
}
}
'入力[長さ]' 'であることが必要である\ 0''(および' '入力[長さ1 ]は '' \ n''であり、 ''式[25]; 'オブジェクトのサイズを超えたインデックス) – wildplasser
strlenは文字ではなく文字列(最初の文字へのポインタ)を取得します。 –
'char式[25] = {NULL};'には意味がありません。 '{'\ 0'}'または '' "' 'に置き換えてください。 – Stargateur