Cast on void pointer

0

The code below was working as expected, but I changed the info type in the structure List from Retangulo* to void* and tried anyway to cast but continue with the following error:

t.c: In function ‘imprimir’:  
t.c:40:38: warning: dereferencing ‘void *’ pointer   
   printf("Base.....: %.2f\n", l->info->b);  
                                      ^
t.c:40:38: error: request for member ‘b’ in something not a structure or union  
t.c:41:38: warning: dereferencing ‘void *’ pointer  
   printf("Altura...: %.2f\n", l->info->h);  
                                      ^
t.c:41:38: error: request for member ‘h’ in something not a structure or union  
t.c:42:41: warning: dereferencing ‘void *’ pointer  
   printf("Área.....: %.2f\n\n", l->info->b * l->info->h);  
t.c:42:41: error: request for member ‘b’ in something not a structure or union
t.c:42:54: warning: dereferencing ‘void *’ pointer   
   printf("Área.....: %.2f\n\n", l->info->b * l->info->h);
                                                      ^
t.c:42:54: error: request for member ‘h’ in something not a structure or union

Code:

typedef struct retangulo
{
    float b;
    float h;
} Retangulo;

typedef struct lista
{
    void *info;
    struct lista *prox;
} Lista;

Lista* inserir(Lista* l, float base, float alt)
{

    Lista* novo=malloc(sizeof(Lista));
    Retangulo* ret=malloc(sizeof(Retangulo));

    ret->b=base;
    ret->h=alt;

    novo->info=ret;
    novo->prox=l;

    return novo;
}

void imprimir(Lista* l)
{

    for (; l!=NULL; l=l->prox)
    {
        printf("Base.....: %.2f\n", l->info->b);
        printf("Altura...: %.2f\n", l->info->h);
        printf("Área.....: %.2f\n\n", l->info->b * l->info->h);
    }
}
    
asked by anonymous 04.01.2018 / 04:07

1 answer

1

The error is because the compiler does not know how to handle the info pointer, since it does not point to a specific type of data. So the solution would be cast, for example:

printf("Base.....: %.2f\n", ((Retangulo*) l->info)->b);

But there does not seem to be a need to declare the variable info as void * .

    
04.01.2018 / 12:48