Pointer Conversions in Function Calls
suggest changePointer conversions to void * are implicit, but any other pointer conversion must be explicit. A pointer to an object type may be converted to a pointer to a different object type. If the result is not correctly aligned for the new type, the conversion itself is undefined behavior. When the alignment is suitable, converting the pointer back recovers the original. Reading or writing the object through the new type is still undefined unless the types are compatible or the access is made as a character type.
#include <stdio.h>
void func_voidp(void* voidp) {
printf("%s Address of ptr is %p\n", __func__, voidp);
}
/* Structures have same shape, but not same type */
struct struct_a {
int a;
int b;
} data_a;
struct struct_b {
int a;
int b;
} data_b;
void func_struct_b(struct struct_b* bp) {
printf("%s Address of ptr is %p\n", __func__, (void*) bp);
}
int main(void) {
/* Implicit ptr conversion allowed for void* */
func_voidp(&data_a);
/*
* The structures have identical members but are not compatible types.
* This call only prints the address, so it does not access data_a as a
* struct_b. Using bp->a inside func_struct_b would be undefined behavior.
*/
func_struct_b((struct struct_b*)&data_a);
return 0;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents