Reputation: 12583
This is quite a long introduction to a simple question, but otherwise there will be questions of the type "Why do you want to handle void pointers in C++? You horrible person!". Which I'd rather (a)void. :)
I'm using an C library from which I intially retrieve a list of polygons which it will operate on. The function I use gives me an array of pointers (PolygonType**
), from which I create a std::vector<MyPolyType>
of my own polygon class MyPolyType
. This is in turn used to create a boost::graph
with node identifiers given by the index in the vector.
At a later time in execution, I want to calculate a path between two polygons. These polygons are given to me in form of two PolygonType*
, but I want to find the corresponding nodes in my graph. I can find these if I know the index they had in the previous vector form.
Now, the question: The PolygonType
struct has a void*
to an "internal identifier" which it seems I cannot know the type of. I do know however that the pointer increases with a fixed step (120 bytes). And I know the value of the pointer, which would be the offset of the first object. Can I use this to calculate my index with (p-p0)/120
, where p
is the address of the Polygon I want to find, and p0
is the offset of the first polygon? I'd have to cast the adresses to int
s, is this portable? (The application can be used on windows and linux)
Upvotes: 3
Views: 1311
Reputation: 96241
Given that the pointer is pointing to an "internal identifier" I don't think you can make any assumptions about the actual values stored in it. If the pointer can point into the heap you may be just seeing one possible set of values and it will subtly (or obviously) break in the future.
Why not just create a one-time reverse mapping of PolygonType*
-> index
and use that?
Upvotes: 2
Reputation: 133004
You cannot substract two void pointers. The compiler will shout that it doesn't know the size. You must first cast them to char pointers (char*
) and then substract them and then divide them by 120. If you are dead sure that your object's size is actually 120, then it is safe( though ugly) provided that p and p0 point to objects within the same array
I still don't understand why p0 is the offset? I'd say p is the address of your Polygon, and p0 is the address of the first polygon... Am I misunderstanding something?
Upvotes: 6