【问题标题】:Array of pointers - reading from a file - crashes指针数组 - 从文件中读取 - 崩溃
【发布时间】:2023-03-27 05:14:01
【问题描述】:

你能指出我做错了什么吗?

我正在尝试编写一些代码,这些代码将从文本文件中读取数据并将这些数据保存到指针数组中,这些指针指向结构。我不使用任何全局标识符是至关重要的。

这是我写的,但每次函数 nactiProdukty (readProductsfromFile) 结束时都会出现错误:First-chance exception at 0x73006500 in ConsoleApplication3.exe: 0xC0000005: Access violation executing location 0x73006500。但是从文件中读取似乎工作正常。

#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);
  }
}

【问题讨论】:

  • 这是 C++ 而不是 C#,使用 C++ 标签发布。
  • 并且不要在标题中包含标签。这就是标签字段的用途。 =)
  • @Alex 是什么让你觉得这是 C++?虽然我同意它也不是 C#
  • -1 您的代码格式还有很多不足之处。
  • 我已经修复了,请注意新的格式并在以后模仿它:合理的缩进,统一的缩进,所有块缩进,代码中没有不必要的大间隙

标签: c arrays file pointers


【解决方案1】:

线

while(fscanf(data,"%s %d") != EOF){

错了。来自fscanf 手册页:

如果格式转换规范的数量超过指针的数量 参数,结果未定义。

崩溃是一种有效且常见的未定义结果。您可以通过为fscanf 提供要写入的变量来解决此问题,然后忽略结果:

int i;
char s[20];
while(fscanf(data,"%s %d", s, i) == 2){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多