私のコードは動作しますが、私の質問はこの動的割り当てが正しいかどうかです。それはうまく動作し、すべてが大丈夫ですが、私はそれが正しいと確信していません。この再割り当て方法は正しいですか
StudentDynamic* pStudents = NULL;
char auxfirstName[255], auxlastName[255];
float auxGrade;
FILE* pFile = fopen("InitialDB.txt", "r");
if (pFile == NULL)
{
printf("Could not open file or is empty! Exiting...");
exit(2);
}
int i = 0;
pStudents = (StudentDynamic*)malloc(sizeof(StudentDynamic) * 1);
while (!feof(pFile))
{
fscanf(pFile, "%s", auxfirstName);
pStudents[i].firstName = (char*)malloc(strlen(auxfirstName) + 1);
strcpy(pStudents[i].firstName, auxfirstName);
fscanf(pFile, "%s", auxlastName);
pStudents[i].lastName = (char*)malloc(strlen(auxlastName) + 1);
strcpy(pStudents[i].lastName, auxlastName);
fscanf(pFile, "%f", &auxGrade);
pStudents[i].grade = auxGrade;
i++;
pStudents = (StudentDynamic*)realloc(pStudents, sizeof(StudentDynamic) * (i + 1));
}
nStudents = i;
fclose(pFile);
[malloc()の返り値をC言語でキャストしない理由についてのこの記事を参照してください。](https://stackoverflow.com/q/605845/2173917) –
"while(!feof(file))"常に間違っていますか?(https://stackoverflow.com/q/5431941/2173917) –
malloc + strcpyの代わりに 'strdup'を使用してみませんか? –