**已关闭。**此问题需要debugging details。当前不接受答案。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
19小时前关闭
Improve this question
我已经编写了一个基本的ATM机程序,其中包含创建帐户,检查余额,进行交易等功能,但还没有完成。我使用文件来存储数据并读取它。读取_account函数,write_account函数用于创建新帐户,no_of_accounts函数用于获取文件中所有正常工作的帐户数量。问题在于find_account_number,它应该以帐号为参数,并返回帐号所在的索引。
#include <stdio.h>
#include <stdlib.h>
#define MAX_act 100
typedef struct{
long account_number;
int CVV;
int PIN;
float balance;
long phone_number;
} act;
void write_account(long account_number, int CVV, int PIN, long phone_number)
{
FILE *f;
act *account = (act*) malloc(sizeof(act));
f = fopen("account_data", "a");
*account = (act) { account_number, CVV, PIN, 0, phone_number};
fprintf(f, "%ld %d %d %.2f %ld\n", account->account_number, account->CVV, account->PIN, account->balance, account->phone_number);
fclose(f);
}
act* read_accounts(void){
FILE *f;
int i = 0;
f = fopen("account_data", "r");
act *accounts = (act*) malloc(sizeof(act)*MAX_act);
while(fscanf(f, "%ld %d %d %f %ld", &accounts[i].account_number, &accounts[i].CVV, &accounts[i].PIN, &accounts[i].balance, &accounts[i].phone_number) == 5){
i++;
}
fclose(f);
return accounts;
}
int no_of_accounts(void){
FILE *f;
int i = 0;
act *accounts;
f = fopen("account_data", "r");
while(fscanf(f, "%ld %d %d %f %ld", &accounts->account_number, &accounts->CVV, &accounts->PIN, &accounts->balance, &accounts->phone_number) == 5)
i++;
free(accounts);
return i;
}
int find_account_no(long account_number, int no_of_accounts, act *accounts){
int i = 0;
act *account = accounts;
printf("yes, it's called\n");
for(i=0; i< no_of_accounts; i++){
printf("%ld\n", account[i].account_number);
if(account[i].account_number == account_number)
return i;
}
return -1;
}
int main(){
//write_account(123, 111, 222, 939);
//write_account(321, 111, 222, 939);
//write_account(123, 111, 222, 939);
find_account_no(123, no_of_accounts(), read_accounts());
printf("%d\n", no_of_accounts());
}
所以在函数find_account_number中,我传递了一个帐号,没有0f accounts和一个指向数组的指针,其中使用read_accounts函数存储帐户数据。bug在哪里?输出不是。
1条答案
按热度按时间f0brbegy1#
问题出在
find_account_number
上,它应该接受一个帐号作为参数,并返回帐号所在的索引。此函数调用不分配任何内存的
no_of_accounts()
在其他函数中,你分配内存。如果你启用编译器警告,这个错误就会被发现--总是必要的。