Reputation: 135
I have the following union:
union uval_t
{
size_t _size;
void* _pointer;
uint32_t _tid[2];
};
If I now do the following:
std::vector<uval_t*> uvalPointerVec;
uvalPointerVec.push_back((uval_t*)malloc(sizeof(uval_t) * 1000));
How do I access the array in the union correctly? Let's say my first union value is of type size_t
. I can do:
uvalPointerVec[0]->_size = 1000;
But what are the best practices to do pointer arithmetic with the union pointer to access the elemets?
Example: Can I do the following to access the first union pointer in my vector and access the location after where my _size
was was stored?
uvalPointerVec[0][1]->_tid[0] = 42;
uvalPointerVec[0][1]->_tid[1] = 24;
uvalPointerVec[0][2]->_pointer = somePointer;
Do I get the following result with this?
| 1000 | 42 | 24 | 0x... |
^ ^
| |_First union value
|_union pointer
Edit: I think my question is answered (did not try it yet) but a little bit more context for all the confused. I implement the physical algebra of an database system. The Scan operator for example reads data stored in memory and saves all tuples in some kind of data structure. Currently the Scan operator is implemented as template and must work for different page layouts (row store [nsm=n-ary store model] vs column store[pax=partition attributes across]). The data structure which stores the retrieved tuples must work for both page layouts aswell. In NSM (e.g., row-stores) I can access a tuple by a single pointer to that tuple since all attributes are stored in a consecutive manner. For the other page layout I need two integers to exactly adress a tuple: a page number and a record number on that page (tid). Size is needed for some optimization reasons I dont want to discuss now. So if I now want to Scan a NSM page I can store pointer to tuples in my data structure, if i Scan a PAX-page I can reuse the same data structure and instead of storing pointers I store pairs of PageNo/TupleNo.
That is the short version of what I want to achieve
Upvotes: 0
Views: 505
Reputation: 108
The correct way would be like this:
vector[i][j].member = value;
Where i is the index to your vector element and j being an index into the array element i.
This is irrelevant to the question but you're using a lot of C rather than C++, I'd suggest replacing your
(uval_t*)malloc(sizeof(uval_t) * 1000)
With the more standard (but still not desireable):
new uval_t[1000]
or an even better and more acceptable:
std::array<uval_t, 1000>() //fixed size
std::vector<uval_t>(1000) //resizable
They are safer and way easier to pass around, they also free themselves when elements are replaced or erased. Array will have equivalent performance and vector coming in close if you make sure to allocate the amount you need beforehand.
Upvotes: 3