简体   繁体   中英

Is it possible to perform arithmetic operation on void pointer with sizeof?

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);

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM