简体   繁体   中英

C values of dynamic array wrong

basically in this code im saving content from a txt file to a dynamic array(until then is all good), but when I try to reallocate memory and add more structs some values in the middle get wrong, always the same ones This is the code I used to save to a dynamic array

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "header.h"

int iniF(guitarra *vg,int *tamvg)
{
int ch=0, i;

FILE *g;

g = fopen("guitarras.txt", "r"); // abrir ficheiro

if(g == NULL)
{
    printf("Erro ao abrir ficheiro %s", "guitarras.txt");
}

while(!feof(g)) //check how many lines the file have
{
    ch = fgetc(g);
    if(ch == '\n')
    {
        (*tamvg)++;
    }
}

fseek(g, 0, SEEK_SET);

vg = malloc(*tamvg * sizeof(guitarra));

for(i=0; i<*tamvg; i++)
{
    fscanf(g, ("%d %f %f %d %s"), &vg[i].id, &vg[i].pdia, &vg[i].valor, &vg[i].estado, &vg[i].nome );
}

fclose(g);
return vg;
}

and this to reallocate

#include <stdio.h>
#include <stdlib.h>
#include "header.h"

 int addguit(guitarra *vg, int *tamvg)
{

int stop=0;


do
{
    vg = realloc(vg, sizeof(guitarra)); //allocating one size of struct guitarra
    printf("Id: ");
    scanf("%d", &vg[*tamvg].id);
    printf("Preco por dia: ");
    scanf("%f", &vg[*tamvg].pdia);
    printf("Valor: ");
    scanf("%f", &vg[*tamvg].valor);
    printf("Estado: ");
    scanf("%d", &vg[*tamvg].estado);
    printf("Nome: ");
    scanf("%s", &vg[*tamvg].nome);
    printf("Deseja adicionar mais guitarras ao stock? Sim[1] Nao[0]: "); //asking if wants to allocate one more
    scanf("%d", &stop);
    (*tamvg)++;
}
while(stop==1);

return vg;
}

the values are simple " 1 1 1 1 a"; " 2 2 2 2 b", and so on, you get it.

heres a print screen of what im talking about

ptrscr of the problem

Your call to realloc does not add the size of one struct to the array. Instead it resizes it to the size of a single struct (see reference for realloc ). The memory for the rest of the array is no longer reserved and can be claimed/modified by other programs. Assuming that tamvg points to the current length of the array, you should have something similar to the following:

vg = realloc(vg, sizeof(guitarra)*(*tamvg+1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM