[英]Array of pointers - reading from a file - crashes
Could you please point me to what am I doing wrong? 您能指出我做错了什么吗?
I am trying to write some code that will read data from a text file and save those data into an array of pointers, that point to to structs. 我正在尝试编写一些代码,这些代码将从文本文件中读取数据,并将这些数据保存到指向结构的指针数组中。 It is critical that I don't use any global identifiers.
请勿使用任何全局标识符,这一点至关重要。
This is what I wrote but every time the function nactiProdukty
( readProductsfromFile
) ends it crasches with an error: First-chance exception at 0x73006500 in ConsoleApplication3.exe: 0xC0000005: Access violation executing location 0x73006500
. 这就是我写的内容,但是每次函数
nactiProdukty
( readProductsfromFile
)结束时,都会出现错误: First-chance exception at 0x73006500 in ConsoleApplication3.exe: 0xC0000005: Access violation executing location 0x73006500
。 But the reading from file seems to be working ok. 但是从文件中读取似乎正常。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct produkt {
char jmeno[20];
int mnozstvi;
int cena;
} tProdukt;
int SpoctiProdukty();
int Generuj(int min, int max);
void nactiProdukty(tProdukt **pole);
void main(){
tProdukt **pole=NULL;
int i;
srand(time(NULL));
nactiProdukty(pole);
printf("test");
scanf("%s");
}
int SpoctiProdukty(){
FILE *data=fopen("data.txt","r");
int count=0;
while(fscanf(data,"%s %d") != EOF){
count++;
}
fclose(data);
return count;
}
int Generuj(int min, int max){
return (rand()%(max-min)+min);
}
void nactiProdukty(tProdukt **pole){
FILE *data=fopen("data.txt","r");
int temp;
int i;
char temps[20];
int pocet=SpoctiProdukty();
//tProdukt **pole;
pole=(tProdukt**)malloc(sizeof(tProdukt*)*pocet);
for (i = 0; i < pocet; i++) {
pole[i]=(tProdukt*)malloc(sizeof(tProdukt));
}
for (i = 0; i < pocet; i++) {
fscanf(data,"%s %d",temps,&temp);
strcpy((*pole[i]).jmeno,temps);
(*pole[i]).cena=temp;
(*pole[i]).mnozstvi=Generuj(10,150);
}
}
The line 线
while(fscanf(data,"%s %d") != EOF){
is wrong. 是错的。 From the fscanf man page:
从fscanf手册页:
If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined.
如果格式转换规范的数量超过了指针参数的数量,则结果是不确定的。
Crashing is a valid and common undefined result. 崩溃是有效且常见的未定义结果。 You can fix this by providing variables for
fscanf
to write to, then ignoring the results: 您可以通过提供要写入
fscanf
变量,然后忽略结果来解决此fscanf
:
int i;
char s[20];
while(fscanf(data,"%s %d", s, i) == 2){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.