Cast in void pointer

Asked

Viewed 211 times

0

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

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);
    }
}
  • 1

    void* cannot be deregistered(dereferenced) since it is a generic pointer. What is the intention to be using void* instead of Retangulo*, whereas you cannot use the pointer without converting it to a specific type first ?

1 answer

1

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

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

But there seems to be no need to declare the variable info as void *.

Browser other questions tagged

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