I was reading this thread: Typecasting variable with another typedef
type_b *sample_b = (type_b *) ((void *) &sample);
Isn’t (void *) extraneous? &sample would return a pointer of type: type_a, which can be cast directly to (type_b *). Why the extra (void *)? I feel it’s wrong, but am not confident enough in my C – hence the extra verification.
Casting the pointer to type
voidhides the pointer’s true type from the compiler so you can cast it to whatever different type you want and the compiler will not have enough information to know if it’s valid or not, thus it will allow it.Without doing this, the compiler will – at a minumum – complain that you are trying to cast a pointer from one type to another incompatible type.
IMPORTANT NOTE:
The original poster of the question you referenced is trying to do something dangerous. The assumption is the alignment of the structures in memory will be the same, allowing them to access the two individual char’s as if they were a single array of two chars. This may be true in theory and will probably work in a small test program, but if this is done in a piece of production code, it will absolutely end in tears and gnashing of teeth at 3am.