Struct pointer cast doubt

Asked

Viewed 146 times

1

I can’t understand the meaning of this cast: the function will execute and returns a type type_t, which is a typedef for void*.

Then is made a cast for header_t*, which is a struct, but I can’t understand how this occurs cast. When I make a cast like this, the function’s return value becomes a type header_t*.

How does the cast values for abstract data type?

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

u32int orig_hole_pos = (u32int)orig_hole_header;

1 answer

1


First of all

header_t* is a pointer to the type header_t.

Answer

The pointers for the void type void* are pointers for 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 the cast (header_t *) ??

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

Example of void type return*

malloc your return is void* because the programmer can set whatever size he wants, so it didn’t make sense for him to have a type with defined size.

Function cast problem returning void*

If you forget to include the header file stdlib.h and call the function malloc you will have problems because in C the standard type is int so would be considered int malloc() and the cast would only hide Warning depending on the compiler.

Browser other questions tagged

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