Inside the structure, there are two int data type variables (nLife, nDamage).
Allocate this as much as MAX through the CreatCharacter() function, and insert values into nLife and nDamage.
Save the input values to a binary file.
The problem is that the saved file is not read with fread.
The curious thing is that reading the binary file immediately after creating it works fine, but there is a problem when only reading it.
Why is this problem occurring?
#define MAX 10
typedef struct
{
int nDamage;
int nLife;
} CHARACTER;
int CreatCharacter(CHARACTER* pCharMan[], int max)
{
for (int i = 0; i < max; i++)
{
pCharMan[i] = (CHARACTER*)malloc(sizeof(CHARACTER));
if (pCharMan[i] == NULL)
{
printf("fail\n");
return 0;
}
pCharMan[i]->nLife = rand() % 51 + 50;
pCharMan[i]->nDamage = 0;
}
return pCharMan;
}
void main()
{
FILE* fp, *op;
srand((unsigned)time(NULL));
CHARACTER* pCharMan[MAX];
CHARACTER* testStruct[MAX];
CreatCharacter(pCharMan, MAX);
// ①
//fp = fopen("charinfo.bin", "wb"); // If ① is not commented out, it works normally.
//fwrite(pCharMan, sizeof(CHARACTER*), MAX, fp);
//fclose(fp);
// ②
op = fopen("charinfo.bin", "rb");
fread(testStruct, sizeof(CHARACTER*), MAX, op); // When ① is commented out and only ② is executed, it fails.
fclose(op); // "charinfo.bin" exists.
}