我试图读取这2个文件并将其内容存储到2个不同的结构中,所以我的程序不需要一遍又一遍地读它,问题是当我尝试运行两个结构时程序崩溃,当我尝试调试它,它显示标题的错误,但是如果我尝试只运行产品文件或销售文件,它工作正常并显示结果。
代码:
#include <stdlib.h>
#include <stdio.h>
typedef struct sellsFile{
int year, month, day, code;
float sell_amount, price;
}sells;
typedef struct productsFile{
int code;
float stock_amount, uni_price, profit;
char type;
}products;
productsFile *read_productsFile(int *q);
sellsFile *read_sellsFile(int *q);
int main(){
int productsSize, sellsSize;
products *v_products;
sells *v_sells;
v_products = read_productsFile(&productsSize);
for(int cont=0;cont<productsSize;cont++){
printf("%d;%c;%.2f;%.2f;%.2f;\n",v_products[cont].code, v_products[cont].type,v_products[cont].stock_amount,v_products[cont].uni_price,v_products[cont].profit);
}
printf("\n\n\n");
v_sells = read_sellsFile(&sellsSize);
for(int cont=0;cont<sellsSize;cont++){
printf("%d/%d/%d %d %.2f %.2f\n",v_sells[cont].year,v_sells[cont].month,v_sells[cont].day,v_sells[cont].code,v_sells[cont].sell_amount,v_sells[cont].price);
}
}
productsFile *read_productsFile(int *q){
(*q) = 0;
FILE *archive;
products *result;
int code;
float stock_amount, uni_price, profit;
char type;
archive = fopen("products.txt", "r");
while(fscanf(archive,"%d;%c;%f;%f;%f;",&code,&type,&stock_amount,&uni_price,&profit) != EOF){
(*q)++;
result = (products *)realloc(result, sizeof(products) * (*q));
result[(*q)-1].code = code;
result[(*q)-1].type = type;
result[(*q)-1].stock_amount = stock_amount;
result[(*q)-1].uni_price = uni_price;
result[(*q)-1].profit = profit;
}
return(result);
}
sellsFile *read_sellsFile(int *q){
int year, month, day, code;
float sell_amount, price;
sells *result;
*q = 0;
FILE *archive;
archive = fopen("sells.txt","r");
while(fscanf(archive,"%d;%d;%d;%d;%f;%f;",&year,&month,&day,&code,&sell_amount,&price) != EOF){
(*q)++;
result = (sells *)realloc(result,sizeof(sells) * (*q));
result[(*q)-1].year = year;
result[(*q)-1].month = month;
result[(*q)-1].day = day;
result[(*q)-1].code = code;
result[(*q)-1].price = price;
result[(*q)-1].sell_amount = sell_amount;
}
return(result);
}
produts文件示例:
12100;P;17.400;2.30;38.80;
12200;P;25.000;23.70;13.58;
12300;P;16.090;17.48;12.75;
销售档案的示例:
2015;1;1;15800;114.000;5.07;
2015;1;1;15600;9.000;9.79;
2015;1;1;12800;32.483;9.71;
答案 0 :(得分:1)
从此代码行中提取未初始化的result
值:
sells *result;
此代码导致未定义的行为:
result = (sells *)realloc(result,sizeof(sells) * (*q));
因为results
以未知值开头。