Dynamic allocation for struct

I need to dynamically allocate space for a structure, but I am not able and do not know of my error is at the time of declaration or allocation, follow the functions consistent with the declaration.

Statement

struct {
    char nome[100];
    char rua[100];
    char cidade[100];
    char estado[100];
    unsigned long int cep;
} dados;

Allocation

void cria_lista(void) {
    dados info;

    info = malloc(sizeof(struct info));
}

Relocation

void insere(void) {
    int aux;
    int posicao;
    posicao = livre();
    if (posicao == -1) {
        printf("\nEstrutura Cheia!!");
        return;
    }
    if (posicao != 0){
        info = realloc(info,1);
    }
    printf("-- Registro %d:\n", posicao);
    printf("\t Nome: ");
    ler_string(busca.nome, 30);
    aux = busca_nome();
    if (aux != 0)
        strcpy(info[posicao].nome, busca.nome);
    printf("\t Rua: ");
    ler_string(info[posicao].rua, 40);
    printf("\t Cidade: ");
    ler_string(info[posicao].cidade, 20);
    printf("\t Estado: ");
    ler_string(info[posicao].estado, 2);
    printf("\t CEP: ");
    scanf("%lu", &info[posicao].cep);
}
Author: Maniero, 2014-11-24

2 answers

You can already see this error:

malloc(sizeof(struct info));

The correct is:

malloc(sizeof(dados));

Do you want to allocate an element there? This is what you are doing after this change. If you want to allocate to more elements need to multiply by the desired amount.

info = realloc(info,1);

Now seems to be a little worse, because info doesn't even seem to exist in this context. If it exists, it should show us. I can't even say what should be right because the code presented makes no sense.


Tem other weird things like unsigned int for ZIP code. Are you gonna make up your mind about this? If the ZIP code starts with zero will you know how to treat to show the right way?

 5
Author: Maniero, 2014-11-26 10:52:46

Hello I solved my question as follows 1-Changing the statement to

struct end{
    char nome[100];
    char rua[100];
    char cidade[100];
    char estado[100];
    unsigned long int cep;
} *info;

2 - making all allocation at once

void cria_lista(void) {
    int i;
    info = malloc (MAX*sizeof(struct end));
    for (i = 0; i < MAX; i++){
        info[i].nome[0] = '\0';
    }
}

Is not yet the ideal answer, but at the moment it works ...

 0
Author: pmargreff, 2014-11-24 23:08:25