Pointer of struct inside a struct

Asked

Viewed 5,855 times

1

I cannot assign value to a variable of a pointer struct within a struct.

My structs:

typedef struct notas{
    float geral;
    float especifica;
}Notas;

typedef struct data{
    int dia,mes,ano;
}Data;

typedef struct local{
    char ender[81];
    int sala;
}Local;

typedef struct candidatos{
    int inscr;
    char nome[81];

    Local *loc;
    Data nasc;
    Notas nota;
}Candidatos;

And the code that should assign values:

void ler_candidatos(Candidatos *A, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("Digite numero de inscriçao: ");
        scanf("%d",&A[i].inscr);
        fflush(stdin);
        printf("Digite o nome: ");
        scanf("%[^\n]",A[i].nome);
        fflush(stdin);
        printf("Digite o endereço: ");
        scanf("%[^\n]",A[i].loc->ender); //erro aqui.
        fflush(stdin);
        printf("Digite a sala: ");
        scanf("%d",&A[i].loc->sala);
        fflush(stdin);
        printf("Digite sua data de nascimento: ");
        scanf("%d %d %d",&A[i].nasc.dia,&A[i].nasc.mes,&A[i].nasc.ano);
        fflush(stdin);
        printf("Digite sua nota geral: ");
        scanf("%f",&A[i].nota.geral);
        fflush(stdin);
        printf("Digite sua nota especifica: ");
        scanf("%f",&A[i].nota.especifica);
        fflush(stdin);
    }
}
  • How is being allocated the object that is received in the parameter A? Whenever you have a type that a pointer to something you will have to allocate space for that something, since what will be saved in that variable or member of a structure is just the pointer and not the die. In general you will have to use a malloc() for this.

  • Hello user18400, Welcome to Stack Overflow :) I separated your code in two to avoid the scroll bar, which disturbs a little the code reading #Ficaadica.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

3

More or less this is what you need to do:

A[i].loc = malloc(sizeof(Local));
scanf("%[^\n]",A[i].loc->ender); //agora o loc aponta para algum lugar preparado p/ receber o ender
printf("Digite a sala: ");
scanf("%d",&A[i].loc->sala);

I put in the Github for future reference.

You need to allocate the memory to the object pointed by the pointer in the element loc. Only the pointer to the die is stored there and not the data. This data needs to be stored in memory and its address will be stored in the pointer. The allocation occurs with malloc().

The way you were trying to access ender and the sala from an undefined location, a memory point that can be considered random.

When you are deleting an element of A you have to remember to release the memory with free().

I didn’t check for other problems, I focused on what was asked.

Browser other questions tagged

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