pointer to nested struct

4

Code:

#include <stdio.h>
#include<stdlib.h>

struct alumno1{  
    int edad1;  
    float nota1;  
};    

struct alumno{
    int edad;  
    float nota;  
    struct alumno1 *alu1;
};


int main(int argc,char **argv){

   struct alumno *alu;

    alu=malloc(sizeof(alu));

    alu->alu1->edad1=12;
    printf("%i",alu->alu1->edad1);

    free(alu);  

    return 0;  
} 

I get an error, in windows it stops working and ubuntu the core dumped that I think means that it is accessing memory positions that do not correspond thanks and a greeting

    
asked by Juan2005 05.04.2018 в 11:30
source

1 answer

5
alu=malloc(sizeof(alu));

This instruction is wrong because alu is a pointer, and consequently sizeof(alu) is going to give you the size of a pointer ... not a structure. The correct thing would be:

alu=malloc(sizeof(*alu));

Even so, you have another problem, which is that with the previous instruction you are reserving memory for the structure alumno . This structure has a pointer of type alumno1 , but the call to malloc is not going to make an additional reservation for this pointer ... that reservation you have to do it by hand:

alu->alu1 = malloc(sizeof(struct alumno1)); // opcion 1
alu->alu1 = malloc(sizeof(*alu->alu1));     // opcion2

Of course then, when releasing the memory, it must be done in reverse order:

free(alu->alu1);
free(alu);
    
answered by 05.04.2018 / 11:44
source