こんばんは、
割り当てに問題があります。
基本的に、与えられたの素因数を計算するプログラムをコーディングする必要がありますstdin。stdinデータは、それを介してのみプログラムに入ることができechoます< file.txt。データのストリームが80文字を超えることはありません(数字であってもなくてもかまいません)。
プログラムで使用する関数はread()、、、でstrotol()ありstrtok()、「無関係な」コードは次のように流れます。
malloc80の初期バイトのメモリを割り当てるために使用します。- 読み取った文字数(そして最後の文字
int)を介して、に格納します。read()\0 - できるだけ多くのメモリを節約するためにメモリを再割り当てし
realloc()ます(この場合は些細なことですが、まあ...)。
ここで注意が必要です。
- データはスペースで区切る必要があるため、チェックする項目の最大数は最大で次のようになります
(n/2)+1。ここnで、は上限nº2で読み取られた文字数です。 longポイントnº1で取得された数の最大サイズの配列を作成します。numbers[0]次の結果で埋めます:strtol(strtok(line, delim), &end, 10)。に追加
1し、ループcounterに入ります。whilewhile((numbers[counter] = strtol(strtok(NULL, delim), &end, 10)) != NULL) { if(!*end) { // Check whether it's 0, 1, negative, prime or extract its factors } else { fprintf(stderr, "\"%s\" is not a non-negative integer", end) } counter++; }
ここで、いくつかの入力とその出力を示します。
入力:echo 1 2 3 4 5 6 7 8 9 10 | ./factors
出力:
1
2
3
2 2
5
2 3
7
2 2 2
3 3
2 5
Segmentation Fault (core dumped).
入力./factors < integers.txt
整数に整数の列が含まれている場合。
出力:
すべての整数は適切に因数分解され、最後に次のように出力されます。
Segmentation Fault (core dumped).
入力:echo abc 12 13 14 15 | ./factors
出力:
"abc" is not a non-negative integer
13
2 7
3 5
Segmentation Fault (core dumped).
入力:echo -1 -2 -3 -4 -5 | ./factors
出力:
"-1" is not a non-negative integer
"-2" is not a non-negative integer
"-3" is not a non-negative integer
"-4" is not a non-negative integer
"-5" is not a non-negative integer
入力:echo abc abc abc | ./factors
出力:
"abc" is not a non-negative integer
(そしてチェックを続けません)。
入力:echo 3 4 0 6 7 | ./factors
出力:
3
2 2
(そしてチェックを続けません)。
私が見る限り、正常なデータストリームの最後に0、非インスタンスまたは基本的に複数のインスタンスが発生すると失敗します。integerinteger
どうすればこれに取り組むことができるのか、そしてなぜそれが明らかにランダムに失敗するのか、何か考えはありますか?
私はCに不慣れであることをあなたに知らせなければなりません...
よろしくお願いします。
================================================== ==
EDIT1:リクエストに応じて、を生成numbers[]し、そこから読み取るコードフラグメントは次のstdinとおりです。
char *line;
char *end;
char *delim = " \n";
int charsread, counter;
line = malloc(80);
charsread = read(0, line, 81);
if (charsread == 0) {
return EX_OK;
}
realloc(line, charsread);
maxelem = (charsread / 2) + 1;
long numbers[maxelem];
numbers[0] = strtol(strtok(line, delim), &end, 10);
if (!*end) {
zeroone(numbers[0]);
}
else {
fprintf(stderr, "\"%s\" is not a non-negative integer\n", end);
}
counter = 1;
while [...]