So to this is part 2 of a question I asked and was answered yesterday. So today I am coming back with a part 2. I am not sure if this should be this somewhere else so if a moderator wants to move it feel free.
So I am not going to reintroduce my problem here, so please go read part 1 Iterating through a vector of stucts's members with pointers and offsets
So I have come up with a solution to the problem so let me post a modified snippet of code that represents the solution I am going for,
#include <iostream>
#include <vector>
// knows nothing about foo
class Readfoo
{
private:
int offSetSize;
char* pchar;
public:
void SetPoint(double* apstartDouble, int aoffSetSize)
{
offSetSize = aoffSetSize;
pchar = static_cast<char*> (static_cast<void*>(apstartDouble));
};
const double& printfoo(int aioffset) const
{
return *(static_cast<double*> (static_cast<void*>(pchar + aioffset*offSetSize)));
};
};
// knows nothing about readFoo
struct foo
{
int a[5];
double b[10];
};
int main()
{
// populate some data (choose b [2] or other random entry.).
std::vector<foo> bar(10);
for(int ii = 0; ii < bar.size(); ii++)
bar[ii].b[2] = ii;
// access b[2] for each foo using an offset.
Readfoo newReadfoo;
newReadfoo.SetPoint(&(bar[0].b[2]), sizeof(foo)/sizeof(char));
for(int ii = 0; ii < bar.size(); ii++)
std::cout<<"\n"<<newReadfoo.printfoo(ii);
return 0;
}
This, in my opinion, is legal, well I suppose that is what I am asking. Since now, in essence, I am converting my 'interpretation' of the struct foo and the vector bar (an array of foos) into a single array of bytes, or chars.
I.e. In this interpretation the data structure is a single array of chars, of foo size times bar size. When I iterate through this with an integral type I am in essence moving to some hypothetical char element (point 4.2 in the answer to part 1). The printfoo function then combines the next 8 bytes to form a double to return.
So is this legal and other than moving out of bounds of the bar vectors is there any reason why this will not work (I have tested it and it has yet to fail.)?