实现自己的sizeof [英] Implement your own sizeof

查看:191
本文介绍了实现自己的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))


解决方案

问得好


  1. 我不明白的方式合并这两个。


  2. 要处理第二个实施是不​​安全


如果用户什么呢

 的sizeof(* PTR)的sizeof(FUNC())

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

  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())

这篇关于实现自己的sizeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆