Dynamic allocation for struct

2

I need to dynamically allocate space for a structure, but I'm not getting it and I do not know my error is at the time of the 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));
}

Reallocation

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);
}
    
asked by anonymous 25.11.2014 / 00:00

2 answers

4

On the face of it you can see this error:

malloc(sizeof(struct info));

The correct one 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 more elements you need to multiply by the amount you want.

info = realloc(info,1);

Now it seems to be a little worse because info does not seem to exist in this context. If it exists, it should show us. I can not say which one should be right because the code presented does not make sense.

There are other weird things like unsigned int to zip code. Are you going to do it? If the zip code starts with zero will you know how to handle it in the right way?

    
25.11.2014 / 00:08
0

Hello, I solved my question as follows 1 - changing the declaration to

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

2 - doing the allocation all at once

void cria_lista(void) {
    int i;
    info = malloc (MAX*sizeof(struct end));
    for (i = 0; i < MAX; i++){
        info[i].nome[0] = '
struct end{
    char nome[100];
    char rua[100];
    char cidade[100];
    char estado[100];
    unsigned long int cep;
} *info;
'; } }

Still not the ideal answer, but it works right now ...

    
25.11.2014 / 00:08