是否可以对具有sizeof的void指针执行算术运算? [英] Is it possible to perform arithmetic operation on void pointer with sizeof?
问题描述
是否可以在不使用强制转换的情况下对void指针执行算术运算?
Is it possible to perform arithmetic operation on void pointer without the use of casting?
如果我有一个使用未知类型的指针和一个指定类型大小的整数的泛型函数.是否可以仅使用两个参数来执行某些指针算术运算?
If I have a generic function that takes a pointer of unknown type and an integer specifying the size of the type. Is it possible to perform some pointer arithmetic with just two arguments?
void* Function( void* ptr, int size);
推荐答案
- 警告-以下内容可能会引起误解.正如其他人在评论中指出的(特别感谢Steve Jessop),与基于转换的双关语相比,以下基于联合的双关语在标准C ++中没有特殊的保证,并且使用强制转换为
char*
的指针进行算术运算可能会更多可移植,使用联合将其转换为整数. - Warning - the below is probably misleading. As indicated by others in comments (special thanks to Steve Jessop) the union-based type pun below has no special guarantees in standard C++ compared with cast-based puns, and using casts to
char*
to do the pointer arithmetic will probably be more portable that using unions to convert to integers.
由于标准C ++中的指针具有类似数组的语义,因此您需要某种形式的类型调整来执行此操作.我将使用基于工会的双关语作弊...
You need some form of type-punning to do this because of the array-like semantics of pointers in standard C++. I will cheat by using union-based puns...
inline void* Ptr_Add (void* p1, std::ptrdiff_t p2)
{
union
{
void* m_Void_Ptr;
std::ptrdiff_t m_Int;
} l_Pun;
l_Pun.m_Void_Ptr = p1;
l_Pun.m_Int += p2;
return l_Pun.m_Void_Ptr;
}
我的库中有这个确切的代码,还有一些其他代码用于执行面向字节的指针算术和按位运算.基于联合的双关语之所以存在,是因为基于转换的双关语可能是脆弱的(优化器中的指针别名分析可能无法发现别名,因此产生的代码行为不当).
I have this exact code in my library, along with some others for doing byte-oriented pointer arithmetic and bitwise operations. The union-based puns are there because cast-based puns can be fragile (pointer alias analysis in the optimiser may not spot the alias, so the resulting code misbehaves).
如果使用IMO的offsetof
,则需要一组与此类似的功能.它们并不是很好,但是比在需要对指针应用偏移量的任何地方进行所有修剪都好得多.
If you use offsetof
, IMO you need a set of functions similar to this. They aren't exactly nice, but they're a lot nicer than doing all the punning everywhere you need to apply an offset to a pointer.
正如ruslik所暗示的那样,GCC中有一个扩展名(如果您不介意非便携式代码)会将void
的大小视为1,因此您可以在void*
上使用+
来添加以字节为单位的偏移量.
As ruslik hints, there is an extension in GCC which (if you don't mind non-portable code) treats the size of a void
as 1, so you can use +
on a void*
to add an offset in bytes.
这篇关于是否可以对具有sizeof的void指针执行算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!