ファイルから文字「A、B、C、D、E」を読み取り、これらの文字のすべてのインスタンスを記録し、大なり記号と小なり記号の間の文字を無視するプログラムを作成しようとしています。 >」。ファイルは正しく開かれたように見えますが、findCommonAnswers() にある for ループは、保護されているか存在しない値にアクセスしているようです。Windows は例外コード c0000005 を提供し、GNU デバッガーは、「0xXXXXX のヒープ ブロックが 6 の要求サイズを過ぎて 0xXXXXX+1 で変更されました」と通知します。番号 6 は、各デバッグで一定です。コードの現在の出力は "-1.#IND" です。以前のバージョンでは、定数 "probabilityArrayLength" を除くすべての項目に対してゼロが返されました。誰かがエラーの性質についての洞察を私に与えることができれば、それは大歓迎です。これが私のコードです:
#include<stdio.h>
#include<stdlib.h>
...
...
int fsize(FILE *fp)
{
int prev = ftell(fp);
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
fseek(fp,prev,SEEK_SET);
return sz;
}
double* findCommonAnswerChoices( )
{
FILE *data;
data = fopen( "F:\\COMP_SCI\\APCalculusBCMultipleChoiceResults.txt", "r" );
int bufferSize = fsize( data ), totalAnswers = 0, instanceOfA = 0, instanceOfB = 0,
instanceOfC = 0, instanceOfD = 0, instanceOfE = 0, probabilityArrayLength =6, bytesRead = 0;
int j = 0 , k;
double probOfA = 0.0, probOfB = 0.0, probOfC = 0.0, probOfD = 0.0, probOfE = 0.0;
double* probabilities = (double*)malloc( probabilityArrayLength*(sizeof(double)) );
char answers[bufferSize];
if( data==NULL )
{
printf( "%d %s %d \n",bufferSize, " ", sizeof(data) );
printf( "Not Enough Memory" );
}
else
{
bytesRead = fread( answers, 0, bufferSize, data );
}
for( j = 0; j<bytesRead; j++ )
{
if( answers[j]=='<' )
{
do
{
j++;
}
while( answers[j]!='>' );
}
switch( answers[j] )
{
case 'A':
instanceOfA++;
break;
case 'B':
instanceOfB++;
break;
case 'C':
instanceOfC++;
break;
case 'D':
instanceOfD++;
break;
case 'E':
instanceOfE++;
break;
default:
break;
}
}
fclose(data);
totalAnswers = ( instanceOfA+instanceOfB+instanceOfC+instanceOfD+instanceOfE );
probOfA = ( (double)instanceOfA/(double)totalAnswers );
probOfB = ( (double)instanceOfB/(double)totalAnswers );
probOfC = ( (double)instanceOfC/(double)totalAnswers );
probOfD = ( (double)instanceOfD/(double)totalAnswers );
probOfE = ( (double)instanceOfE/(double)totalAnswers );
probabilities[0] = (double)probabilityArrayLength;
probabilities[1] = probOfA;
probabilities[2] = probOfB;
probabilities[3] = probOfC;
probabilities[4] = probOfD;
probabilities[5] = probOfE;
return probabilities;
}
int main()
{
double* something = findCommonAnswerChoices();
int size = (int)something[0];
int p;
for( p = 0; p<size; p++ )
{
printf( "%g \n", something[p] );
}
free( something );
return 0;
}