我在结构,动态内存和文件I / O上练习,但我无法理解这段代码有什么问题。我怀疑错误是realloc函数。当我在文件打开后运行程序时,程序崩溃。 我检查了很多次,我想这不是一个与语法相关的问题(特别是对于realloc)。
结构声明:
#define MAXLENPATH 250
#define MAXSTRING 25
typedef struct
{
int ID;
char Name[MAXSTRING];
char Surname[MAXSTRING];
char code[MAXSTRING];
int age;
}person;
获取记录信息的功能:
#include <stdio.h>
#include <stdlib.h>
#include "Data.h"
#include "DataBase.h"
void initRecord(person *Person)
{
printf("Insert ID:\n");
scanf("%d", &Person->ID);
printf("Insert Name:\n");
scanf("%s", Person->Name);
printf("Insert Surname:\n");
scanf("%s", Person->Surname);
printf("Insert Age:\n");
scanf("%d", &Person->age);
printf("Insert code:\n");
scanf("%s", Person->code);
}
主要功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Data.h"
#include "DataBase.h"
int main(void) {
FILE *ts;
char *fpath=NULL;
int pCount=1; //variable to hold database records count
int i=0;
int toAdd=0;
person *personDB=NULL;
fpath="C:\\Users\\Pio\\Desktop\\FILEOP\\MYTXT.txt";
personDB = malloc(pCount*sizeof(person));
//fill the database(in memory)
i=0;
while( i < pCount)
{
printf("Record %d\n",i+1);
initRecord(&personDB[i]); //fill i-th database record
printf("Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );
i++;
if(i == pCount) // check if all records are filled, then ask to user how many records wants and realloc new memory
{
printf("Insert element to add to database records:");
scanf("%d", &toAdd);
personDB=realloc(personDB, toAdd*(sizeof(person)) );
pCount += toAdd;
}
}
//Print structure on file
if ((ts=fopen(fpath, "w")) != NULL)
{
puts("FILE OPENED");
fprintf(ts,"************INFO****************\n");
i=0;
while (i < pCount)
{
fprintf(ts, "Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );
i++;
}
fclose(ts);
}
else
perror("ERROR:");
system("pause");
return EXIT_SUCCESS;
}