dynamic reallocation - struct array

Asked

Viewed 275 times

1

I need to do an exercise where the code allocates the memory as needed, but I need to reallocate an array of struct, only I ended up locking in this part.

My Struct is:

typedef struct{
    char nome[100];
    char endereco[100];
    int numero;
    char telefone[11];
    char sexo;
    char cpf[11];
    data nascimento;
    double saldo;
}cliente;

I created within the function main() the pointer that will receive the address of my struct.

cliente *cliente;

I’ve allotted memory to only 1 position of my struct

cliente = malloc(sizeof(cliente));

During the execution of my code, I reload the memory to receive another "client", using

cliente = (struct cliente*) realloc(cliente, tam*sizeof(cliente));

but when I use the function to show registered clients, they all show up with memory garbage in the variables, except the last one, which I am doing wrong?

  • Just as a note, you can always use realloc, since the first time pass the pointer cliente with NULL. That way it becomes easier to manage because you don’t have to individualize the first case. Still, the error will probably be in the code you are not showing, as what you have shown so far looks good, assuming it was executed in the right order.

1 answer

0

There’s nothing wrong with finding trash after the realloc() because this function does not initialize the allocated RAM memory space.

If you prefer, see calloc().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.