使用指针运算类型的计算规模的另一种方法 [英] Alternate way of computing size of a type using pointer arithmetic

查看:115
本文介绍了使用指针运算类型的计算规模的另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code 100%便携式?

Is the following code 100% portable?

int a=10;
size_t size_of_int = (char *)(&a+1)-(char*)(&a); // No problem here?

std::cout<<size_of_int;// or printf("%zu",size_of_int);

P.S :现在的问题是只为学习目的。所以,请不要给像答案使用的sizeof()

P.S: The question is only for learning purpose. So please don't give answers like Use sizeof() etc

推荐答案

从ANSI-ISO-IEC 14882-2003,第87页(C ++ 03):

From ANSI-ISO-IEC 14882-2003, p.87 (c++03):

75)另一种方式接近指针
  算法是先转换
  指针(县)字符指针(S):在
  该方案的积分值
  前pression增加或减去从
  转换的指针第一
  乘以对象的大小
  原先指向,并且
  结果指针转换回
  原始类型。对于指针
  减法的结果
  性格的差异
  指针同样被分割
  对象的大小原来指出
  以

"75) Another way to approach pointer arithmetic is first to convert the pointer(s) to character pointer(s): In this scheme the integral value of the expression added to or subtracted from the converted pointer is first multiplied by the size of the object originally pointed to, and the resulting pointer is converted back to the original type. For pointer subtraction, the result of the difference between the character pointers is similarly divided by the size of the object originally pointed to."

这似乎表明,在指针差值等于物体的大小。

This seems to suggest that the pointer difference equals to the object size.

如果我们从递增指向一个标量删除UB'ness,把一个到一个数组:

If we remove the UB'ness from incrementing a pointer to a scalar a and turn a into an array:

int a[1];
size_t size_of_int = (char*)(a+1) - (char*)(a);

std::cout<<size_of_int;// or printf("%zu",size_of_int);

那么这个看起来不错。有关对齐要求的条款都与注脚一致,如果调整​​的要求总是由对象的大小整除。

Then this looks OK. The clauses about alignment requirements are consistent with the footnote, if alignment requirements are always divisible by the size of the object.

更新:有趣。正如你们大多数人可能知道,GCC允许指定作为扩展类型明确的定位。但我不能用它打破OP的的sizeof的方法,因为GCC拒绝编译:

UPDATE: Interesting. As most of you probably know, GCC allows to specify an explicit alignment to types as an extension. But I can't break OP's "sizeof" method with it because GCC refuses to compile it:

#include <stdio.h>

typedef int a8_int __attribute__((aligned(8)));

int main()
{
 a8_int v[2];

 printf("=>%d\n",((char*)&v[1]-(char*)&v[0]));
}

该消息是错误:数组元素的对齐比单元尺寸更大

这篇关于使用指针运算类型的计算规模的另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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