Doubt cast struct pointer

1

I can not understand the meaning of this cast : the function will execute and return a type type_t , which is a typedef to void* .

Then a cast is made to header_t* , which is a struct , but I can not understand how this cast occurs. When I make a cast like this, the return value of the function becomes a type header_t* .

How does cast of values for abstract data type work?

header_t *orig_hole_header = (header_t *)lookup_ordered_array(iterator, heap->index);

u32int orig_hole_pos = (u32int)orig_hole_header;
    
asked by anonymous 23.12.2015 / 19:53

1 answer

1

First

header_t* is a pointer to type header_t .

Response

Pointers to type void void* are pointers to any type. They are used when the programmer does not know what kind of information he will receive. That is, if it is a int , char ...

As such these can be converted to any type of pointer.

int i = 5;
void *p = &i;
*p = 4;//Valor de i agora é 4

Why cast (header_t *) ??

For no reason. At least in C it is possible to cast cast% of% to any type of pointer, not adding any necessary information to the programmer (even makes it difficult to read the code), but in C ++ cast is mandatory.

Return type void *

void* your return is malloc because the programmer can define what size you want, so it did not make sense to have a type with a defined size.

Problem casting functions that return void *

If you forget to include the header file void* and call the function stdlib.h you will have problems because in C the default type is malloc being thus considered int and the cast would only hide the warning depending on the compiler .

    
23.12.2015 / 21:31