旧大小的realloc()问题

时间:2018-11-19 21:31:49

标签: c pointers struct malloc realloc

我想从文件中读取很多信息,因此我需要一个动态内存。 这就是为什么我在主体中将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;
}

1 个答案:

答案 0 :(得分:0)

这不是增加数组的方式。

首先

Rechnung++;

很好并且很花哨,但是Rechnung不再是先前调用mallocrealloc返回的指针。因此,您既不能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将变得无效。因此,请使用普通的旧无聊数组索引。