Pointer to struct within a struct

1

I can not assign value to a variable of a pointer of 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);
    }
}
    
asked by anonymous 25.11.2014 / 20:14

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 placed GitHub for future reference .

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

As it was you were trying to access ender and sala from an undefined location, a memory point that can be considered random.

When you're deleting an element of A you'll have to remember to free up memory with free() .

I did not check for other problems, I focused on what was asked.

    
26.11.2014 / 12:40