Dynamic allocation for struct

Asked

Viewed 14,165 times

4

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

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);
}
  • What and where is the error?

2 answers

5


You can see this mistake right away:

malloc(sizeof(struct info));

The correct is:

malloc(sizeof(dados));

Do you want to allocate an element there? That’s what you’re doing after this change. If you want to allocate for more elements you need to multiply by the desired amount.

info = realloc(info,1);

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


There are other weird things like unsigned int for CEP. Will you do it? If the CEP starts with zero will know how to treat to show the right way?

  • I was allocating as data, when the correct would really be like info, thank you for the remark.

  • 1

    I think you’re still making trouble. What may be looking right still has mistakes. But I can’t guarantee without understanding all the code and its real intent. Anyway the solution that you set up changes well what you were doing. If you think you solved, great.

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 - making the whole 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';
    }
}

Still not the ideal answer, but at the moment it works ...

Browser other questions tagged

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