实现自己的sizeof [英] Implement your own sizeof
问题描述
可能重复:结果
一个数据类型的大小,而无需使用的sizeof
块引用>我的一个朋友最近出现了NVIDIA接受采访时,他被要求
里用C实现
自己的sizeof。我试图做同样的实践和成功写入的sizeof的这
一两个不同的定义可以处理变量和其他可以处理的数据类型,但我不能将二者合并。有没有什么办法这样做呢?此外,是否有可能实现一个完整的的sizeof
用C手柄类型,如
INT
,字符
等的#define my_sizeof(类型)((为size_t)(((键入*)0)+ 1))
处理诸如
变量X
的#define my_sizeof(VAR)(为size_t)((字符*)(安培; VAR + 1) - (字符*)(安培; VAR))
解决方案问得好
我不明白的方式合并这两个。
要处理第二个实施是不安全
如果用户什么呢
的sizeof(* PTR)的sizeof(FUNC())
Possible Duplicate:
size of a datatype without using sizeofOne 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 ofsizeof
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 completesizeof
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())
这篇关于实现自己的sizeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!