Reputation: 4169
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);
Upvotes: 1
Views: 1949
Reputation:
char*
to do the pointer arithmetic will probably be more portable that using unions to convert to integers.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).
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.
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.
Upvotes: 1
Reputation: 73219
No, because the compiler doesn't know the size of the item(s) the void pointer is pointing to. You can cast the pointer to (char *) to do what you want above.
Upvotes: 4