Possible Duplicate:
size of a datatype without using sizeof
One of my friend recently appeared in NVIDIA interview where he was asked to implement his own sizeof in C
. I tried to do the same for practice and successfully write two different definitions of sizeof
one of which can handle variables and other can handle datatypes but I am unable to merge the two. Is there any way to do so? Also, is it possible to implement a complete sizeof
in C.
Handle types like int
, char
etc
#define my_sizeof(type) ((size_t)(((type *)0) + 1))
Handles variables like x
#define my_sizeof(var) (size_t)((char *)(&var+1)-(char*)(&var))
Good question
I don't see a way to merge the two.
The implementation to handle the second is unsafe
what if the user does
sizeof (*ptr)
sizeof (func())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With