Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement your own sizeof [duplicate]

Tags:

c

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))
like image 674
Ravi Gupta Avatar asked Jun 02 '12 14:06

Ravi Gupta


1 Answers

Good question

  1. I don't see a way to merge the two.

  2. The implementation to handle the second is unsafe

what if the user does

sizeof (*ptr)

sizeof (func())
like image 90
Saurabh Avatar answered Nov 12 '22 13:11

Saurabh