If I have a struct
with members int a, b, c;
, I can get the byte offset of each member using offsetof(structName, member)
.
Now, if I have a struct
with a vector<int> { a, b, c }
, I can get the offset of the vector
using offsetof(structName, vectorName)
.
Knowing this, is this operation:
offsetof(structName, vectorName) + sizeof(vector<int>) + sizeof(int)*2
a valid way of getting the offset of b
?
First off, b
is the vector
's 2nd element, but sizeof(int)*2
would return the offset of the 3rd element instead.
But more importantly, the vector
's element array is not stored inside the vector
class itself, so using offsets relative to the vector
itself will not work. The actual array is stored elsewhere in memory, and then the vector
contains an internal member that is a pointer to the array.
As such, all you really need to determine the offset of an element in the vector
's array is sizeof(vector::value_type) * index
(where index
is 1 for b
in your example). However, to actually access the element using that offset, you first need the pointer to the array itself. You can use the vector
's data()
method, or operator[]
, to get that pointer, eg:
structName *s = ...;
vector<int> *v = reinterpret_cast<vector<int>*>(
reinterpret_cast<unsigned char*>(s)
+ offsetof(structName, vectorName)
);
int *arr = v->data();
// or: int *arr = &(*v)[0];
size_t offset = sizeof(int) * index;
int *element = reinterpret_cast<int*>(
reinterpret_cast<unsigned char*>(arr)
+ offset
);
// use element as needed...
However, you really shouldn't use offsetof
like this. The above can be greatly simplified to this instead:
structName *s = ...;
int *element = s->vectorName.data() + index;
// or: int *element = &(s->vectorName[index]);
// use element as needed...