便携和安全的方式来添加字节偏移到任何指针 [英] Portable and safe way to add byte offset to any pointer
问题描述
我在使用C ++时很新,并且没有掌握语言的所有复杂和微妙之处。
最常见的是什么>便携,正确和安全方式向C ++ 11中任何类型的指针添加任意字节偏移量
someType * ptr;
int offset = 12345 / * bytes * /;
ptr = ptr + offset; //< -
在Stack Overflow和谷歌,但他们都提出了不同的东西。我遇到的一些变体:
-
ptr = SomeType *)(((char *)ptr)+ offset);
-
投放至
unsigned int
:ptr =(SomeType *)((unsigned int)ptr)+ offset);
-
ptr = SomeType *)((size_t)ptr)+ offset);
-
size_t
和ptrdiff_t
总是与指针的大小一致。因此,这些类型应该用作大数组的索引,用于存储指针和指针运算。 - 关于CodeProject的关于size_t和ptrdiff_tptr =(SomeType *)((size_t)ptr +(ptrdiff_t)offset);
-
或类似于上述,但使用> > :
ptr =(SomeType *)((intptr_t)ptr +(ptrdiff_t)offset);
-
只转换到
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:
ptr = (SomeType*)(((char*)ptr) + offset);
Cast to
unsigned int
:ptr = (SomeType*)((unsigned int)ptr) + offset);
ptr = (SomeType*)((size_t)ptr) + offset);
"The size of
size_t
andptrdiff_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 CodeProjectptr = (SomeType*)((size_t)ptr + (ptrdiff_t)offset);
Or like the previous, but with
intptr_t
instead ofsize_t
, which is signed instead of unsigned:ptr = (SomeType*)((intptr_t)ptr + (ptrdiff_t)offset);
Only cast to
intptr_t
, sinceoffset
is already a signed integer andintptr_t
is notsize_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屋!