【发布时间】:2015-05-24 16:52:26
【问题描述】:
我正在尝试存储一个如下所示的文本文件:
Headphones-750, TV-1500, Keyboard-1200, Tablet-80, Speakers-400, DVD-250, Streamer-550, Mouse-50;
放入一个def类型的数组中:
typedef struct item{
char* name;
int price;
}item;
typedef struct item{
char* name;
int product_code;
int price;
}item;
item *getProducts(){
FILE *fp;
fp = fopen("machinedata.txt", "r");
if (fp == NULL)
{
printf("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
static item products[8];
int row = 0;
while (fscanf(fp,"%50[^-],%10[^,]",products[row].name,products[row].price) ){
products[row].product_code = row;
row++;
}
return products;
}
但它不会工作。我如何创建这个typedef item 数组并返回一个指向数组的指针,我将能够从其他函数特别是 main() 操作/打印该数组。
我正在用 C 编码,请寻找 C 指导
【问题讨论】:
-
不要定义结构。结果是代码混乱、误解和编译器名称空间混乱。
-
您没有为
products[row].name分配任何内存,因此将未初始化的指针传递给fscanf