执行sizeof操作符 [英] implementation of sizeof operator

查看:165
本文介绍了执行sizeof操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试推行sizeof操作符。我这样做了。

I have tried implementing the sizeof operator.. I have done in this way..

#define my_sizeof(x) ((&x + 1) - &x)

但它总是在给结果为1,无论是数据类型。

But it always ended up in giving the result as '1' for either of the data type..

我已经那么GOOGLE了它为这个..我发现code 类型强制转换

I have then googled it for this.. and i found the code typecasted

#define my_size(x) ((char *)(&x + 1) - (char *)&x)

而code为工作,如果它是类型强制转换。我不明白为什么。这code也是填充结构完美。

And the code is working if it is typecasted.. I dont understand why.. This code is also PADDING a STRUCTURE perfectly..

这也是工作

#define my_sizeof(x) (unsigned int)(&x + 1) - (unsigned int)(&x)

任何人都可以请解释它是如何工作的,如果类型强制转换,如果没有类型强制转换?

Can anyone please explain how is it working if typecasted and if not typecasted?

在此先感谢..

推荐答案

指针相减的结果是在的元素的而不是字节。因此,第一八佰伴pression根据定义的计算结果为 1

The result of pointer subtraction is in elements and not in bytes. Thus the first expression evaluates to 1 by definition.

这一边,你真的应该在宏中使用括号:

This aside, you really ought to use parentheses in macros:

#define my_sizeof(x) ((&x + 1) - &x)
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

否则,尝试使用 my_sizeof()在离pression可能会导致错误。

Otherwise attempting to use my_sizeof() in an expression can lead to errors.

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

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