我想从文件中读取大量信息,所以我需要动态内存。 这就是为什么我在 main 中使用 malloc 作为我的结构。 我想对从文件中获得的每个新行进行重新分配,但他说“realloc():无效的旧大小”,甚至没有重新分配一次。
typedef struct{
int anzahl;
int ANR;
char MHD[10];
char Bezeichnung[20];
char VPE[5];
float Preis;
float gesamtpreis;
}Ware;
int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung[] = " :,;\n\0=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
count++;
}
fclose(datei_lesen);
if(count == 0)
{
return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
fputs(zeilen_lesen,datei_lesen);
formatierer = strtok(zeilen_lesen,trennung);
if(atoi(formatierer) >= 100000)
{
Rechnung->ANR = atoi(formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->MHD,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->Bezeichnung,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->VPE,formatierer);
formatierer = strtok(NULL,trennung);
Rechnung->Preis = atoi(formatierer);
Rechnung = realloc(Rechnung,1*sizeof(Ware));
//Rechnung = (Ware*) realloc(Rechnung,1);
Rechnung++;
}
}
fclose(datei_lesen);
return 0;
}
int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;
initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}
最佳答案
这不是增长数组的方式。
首先
Rechnung++;
很好,但 Rechnung
不再是先前调用 malloc
或 realloc
返回的指针。所以你既不能realloc
也不能free
它。
第二,
Rechnung = realloc(Rechnung,1*sizeof(Ware));
如果您希望无论如何都将数组的大小始终保留为 1 个元素,就可以了。如果您希望尺寸增加,则需要输入新的尺寸。
典型的数组增长循环通常如下所示:
Data *array = NULL; // note it's fine to realloc a NULL
size_t size = 0;
while (fgets(...)) {
size_t new_size = size + 1;
Data *new_array = realloc(array, sizeof(Data) * new_size);
if (new_array == NULL) {
// report an error, exit, abort, try again, whatever
// note having a separate `new_array` variable allows you
// to retain old data in `array` in the case of `realloc` erroring on you
} else {
array = new_array;
array[size].foo = make_foo();
array[size].bar = make_bar();
size = new_size;
}
}
请注意,您从不递增array
,因为您无法将递增的array
传递给realloc
。你不能也有这样的东西:
Data *array = malloc(sizeof(Data));
Data *current = data;
while (...) {
...
current->foo = make_foo();
current->bar = make_bar();
array = realloc(array, sizeof(Data) * new_size);
current++;
}
因为realloc
可能会返回一个与传递的指针不同的指针,并且current
将变得无效。因此,请使用普通的老式无聊数组索引。
关于c - realloc() 与旧大小的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382931/