Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ offsetof char* arithmetic

In this answer, int8_t* is used for (byte) pointer arithmetic:

std::size_t offset = offsetof(Thing, b);
Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<int8_t*>(ptr) - offset);

I've always used char* in the past but the comments are really confusing, and nobody responded, so I posted this separate question.

Is char* valid, and the preferred way of doing these calculations?

like image 260
Karoly Horvath Avatar asked Nov 23 '15 13:11

Karoly Horvath


1 Answers

You must use char*: the behaviour on using a reinterpret_cast with int8_t* on a pointer to something that is not an int8_t is undefined. Casting to char* can be viewed as an exception to the rule.

Pre C++14, char can be a 1's complement type with range -127 to +127. int8_t must be 2's complement. Even C++14 and onwards, I can't see why the types are related: char can still be either a signed or an unsigned type.

like image 186
Bathsheba Avatar answered Sep 19 '22 22:09

Bathsheba