便携和安全的方式来添加字节偏移到任何指针 [英] Portable and safe way to add byte offset to any pointer

查看:139
本文介绍了便携和安全的方式来添加字节偏移到任何指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用C ++时很新,并且没有掌握语言的所有复杂和微妙之处。



最常见的是什么>便携,正确和安全方式向C ++ 11中任何类型的指针添加任意字节偏移量

  someType * ptr; 
int offset = 12345 / * bytes * /;
ptr = ptr + offset; //< -






在Stack Overflow和谷歌,但他们都提出了不同的东西。我遇到的一些变体:


  1. 投放到 char *

      ptr = SomeType *)(((char *)ptr)+ offset); 


  2. 投放至 unsigned int

      ptr =(SomeType *)((unsigned int)ptr)+ offset); 


  3. 投射到 size_t

      ptr = SomeType *)((size_t)ptr)+ offset); 


  4. size_t ptrdiff_t 总是与指针的大小一致。因此,这些类型应该用作大数组的索引,用于存储指针和指针运算。 - 关于CodeProject的关于size_t和ptrdiff_t

      ptr =(SomeType *)((size_t)ptr +(ptrdiff_t)offset); 


  5. 或类似于上述,但使用> > :

      ptr =(SomeType *)((intptr_t)ptr +(ptrdiff_t)offset); 


  6. 只转换到 intptr_t 由于 offset 已是有符号整数,因此 intptr_t 不是 size_t

      ptr =(SomeType *)((intptr_t)ptr)+ offset); 


在所有这些情况下,使用旧的C风格的cast,或者它是更安全还是更便携的使用 static_cast reinterpret_cast / p>

我应该假设指针值本身是无符号或有符号?

解决方案

我会使用类似:

  unsigned char * bytePtr = reinterpret_cast< unsigned char *>(ptr); 
bytePtr + = offset;


I'm quite new at working with C++ and haven't grasped all the intricacies and subtleties of the language.

What is the most portable, correct and safe way to add an arbitrary byte offset to a pointer of any type in C++11?

SomeType* ptr;
int offset = 12345 /* bytes */;
ptr = ptr + offset;             // <--


I found many answers on Stack Overflow and Google, but they all propose different things. Some variants I have encountered:

  1. Cast to char *:

    ptr = (SomeType*)(((char*)ptr) + offset);
    

  2. Cast to unsigned int:

    ptr = (SomeType*)((unsigned int)ptr) + offset);
    

  3. Cast to size_t:

    ptr = (SomeType*)((size_t)ptr) + offset);
    

  4. "The size of size_t and ptrdiff_t always coincide with the pointer's size. Because of this, it is these types that should be used as indexes for large arrays, for storage of pointers and pointer arithmetic." - About size_t and ptrdiff_t on CodeProject

    ptr = (SomeType*)((size_t)ptr + (ptrdiff_t)offset);
    

  5. Or like the previous, but with intptr_t instead of size_t, which is signed instead of unsigned:

    ptr = (SomeType*)((intptr_t)ptr + (ptrdiff_t)offset);
    

  6. Only cast to intptr_t, since offset is already a signed integer and intptr_t is not size_t:

    ptr = (SomeType*)((intptr_t)ptr) + offset);
    

And in all these cases, is it safe to use old C-style casts, or is it safer or more portable to use static_cast or reinterpret_cast for this?

Should I assume the pointer value itself is unsigned or signed?

解决方案

I would use something like:

unsigned char* bytePtr = reinterpret_cast<unsigned char*>(ptr);
bytePtr += offset;

这篇关于便携和安全的方式来添加字节偏移到任何指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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