因此,任务是读取文件并将数据推送到结构中。数据文件为:
babe 12 red 12
deas 12 blue 12
dsa 12 red 512
bxvx 15 blue 52
reed 18 black 15而代码就是这样
struct shoes {
char name[8];
int size;
char color[8];
int price;
};
//open file
shoes *item=(struct shoes*)malloc(sizeof(struct shoes));
for (i=0; !feof(file); i++) {
item=(struct shoes*)realloc(item,sizeof(struct shoes)+i*sizeof(struct shoes));
fscanf(file,"%s %i %s %i\n",(item+i)->name,(item+i)->size,(item+i)->color,(item+i)->price);
}但是程序每次都会崩溃。dbg表示:当前上下文中没有符号"item“。error在哪里?
发布于 2013-04-04 01:29:46
你的代码有一些bug: 1)除非你正在用C++编译器编译,否则你需要一个鞋的类型定义函数...但是您应该已经标记了这个C++。2) feof不会返回false,直到实际尝试读取文件末尾以外的内容,因此您的代码会使鞋1的数组变得太大。3)将int传递给fscanf,而不是它们的地址。
如果编译为C代码,而不是C++代码,那么在malloc和realloc上的强制转换是不必要的,建议不要使用它们。还有一些其他的风格问题会让你的代码变得更难理解。试试这个:
typedef struct {
char name[8];
int size;
char color[8];
int price;
} Shoe;
// [open file]
Shoe* shoes = NULL; // list of Shoes
Shoe shoe; // temp for reading
for (i = 0; fscanf(file,"%s %i %s %i\n", shoe.name, &shoe.size, shoe.color, &shoe.price) == 4; i++)
{
shoes = realloc(shoes, (i+1) * sizeof *shoes);
if (!shoes) ReportOutOfMemoryAndDie();
shoes[i] = shoe;
}发布于 2013-04-04 01:14:12
问题在于,您没有传递指向要使用fscanf读取的整数的指针,而是传递了整数本身。
fscanf将它们视为指针。他们指的是哪里?谁知道呢--整数没有初始化,所以它们可以指向任何地方。因此,使用CRASH。
解决方法如下:
fscanf(file,"%s %i %s %i\n",
(item+i)->name,
&((item+i)->size),
(item+i)->color,
&((item+i)->price));请注意,对于name和color,您不需要相同的方法,因为数组退化为指针,所以您已经传递了正确的内容。
请考虑抛弃item+i表示法;当随意阅读代码时,item[i]更清晰、更容易理解:
fscanf("%s %i %s %i\n",
item[i].name,
&item[i].size,
item[i].color,
&item[i].price);发布于 2013-04-04 01:04:05
你确定调试器是这么说的吗?我很惊讶它竟然被编译了..。
你想要:
struct shoes *item如果你没有证明你的结构的类型定义,你必须在每次引用它的时候显式地说"struct“。
第二个注意事项:
item=(struct shoes*)realloc(item...不要从realloc()中分配与传入的指针相同的指针。如果重新分配失败,它将返回NULL,这可能会杀死您。您应该确保同时检查初始malloc()和realloc()的结果
第三点:
您需要将int的地址传递给fscanf()。
fscanf(file,"%s %i %s %i\n",(item+i)->name,&((item+i)->size),(item+i)->color,&((item+i)->price));https://stackoverflow.com/questions/15793615
复制相似问题