c++ - 使用指针算法计算类型大小的替代方法

标签 c++ c pointers portability casting

以下代码是否 100% 可移植?

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:此题仅供学习。所以请不要给出像 Use sizeof()

这样的答案

最佳答案

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

"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."

这似乎表明指针差异等于对象大小。

如果我们从递增指向标量 a 的指针中删除 UB'ness 并将 a 转换为数组:

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

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

那么这看起来没问题。关于对齐要求的条款与脚注一致,如果对齐要求总是能被对象的大小整除。

更新:很有趣。大多数人可能都知道,GCC 允许将类型的显式对齐指定为扩展。但我不能用它破坏 OP 的“sizeof”方法,因为 GCC 拒绝编译它:

#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]));
}

消息是错误:数组元素的对齐方式大于元素大小

关于c++ - 使用指针算法计算类型大小的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3387021/

相关文章:

c++ - tbb::concurrent_unordered_multimap 中的错误?即使是单线程,条目也会丢失

c++ - CRTP std::is_default_constructible 未按预期工作

c++ - 交错式 MPI Isend/Recv 的安全保证

c - 为什么在将新元素分配给 char 指针时似乎不需要 "realloc"?

c - 需要二维数组的解释(+传递给函数)

java - 指针如何与 Java 中的原始类型一起使用?

c++ - 是 case statement1 + statement2 : poor coding?

c - 在 C 中重复使用 getchar() 时出现的问题

c - 在c中返回一个数组

pointers - 嵌套数组结构的指针或无指针之间的混淆