我正在写一个简单的银行应用程序c 它将信息保存在一个文件中。 我想在每次应用程序运行时加载文件,并将文件中的信息添加到结构中,为此,我写了两个函数,称为“loadfile”和“分配”这个bug是关于什么的?结构,指针,动态内存分配,C
在函数“loadfile “如果我对注释行取消注释,操作系统会在我的脸上抛出”停止工作“:|
你能帮我吗? 当我在“loadfile”中使用(acc + i)时,出现错误。 是否有语法问题? :o 谢谢
typedef struct {
char name[20];
int id;
int balance;
char branch[10];
} account;
account *acc;
int allocate (account *acc) {
int num = 0 ;
char tempname[20],tempbranch[10];
int tempid = -1 ,tempbalance;
FILE *file;
file = fopen("D://bank.txt","r");
while (!feof(file)) {
fscanf(file,"%s %d %d %s ",tempname, &tempid, &tempbalance, tempbranch);
if (tempid != -1)
num++;
}
acc = (account *) realloc (acc, num * sizeof(account));
fclose(file);
printf(" num in allocate function : %d",num);
return num;
}
int loadfile (account *acc) {
int num = allocate(acc);
char tempname[20],tempbranch[10];
int tempid ,tempbalance;
if (num != 0) {
int i = 0 ;
FILE *file;
file = fopen("D:\\bank.txt","r+");
for (i = 0 ; !feof(file) && i < num ; i++) {
fscanf(file,"%s ",tempname);
fscanf(file,"%d ",&tempid);
fscanf(file,"%d ",&tempbalance);
fscanf(file,"%s ",tempbranch);
printf("\n i is %d \n",i);
/* strcpy(((acc+i)->name) , tempname);
(acc+i)->id = tempid;
(acc+i)->balance = tempbalance;
strcpy(((acc+i)->branch) , tempbranch); */
}
fclose(file);
}
return num;
}
[为什么 - 是 - 同时-FEOF文件,总是出错(http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – LPs
使用全局'account * acc;'IE'int allocate(account * acc){' - >'int allocate(void){' – BLUEPIXY
不要强制返回void *'函数! – Stargateur