Reputation: 1586
In my code Graph
is a class having a member node
, which is a structure. When I do
unsigned int id = ((unsigned int)n - (unsigned int)_nodes) / sizeof(Graph::node);
I get the following error (compiled on 64-bit Linux):
error: cast from ‘Graph::node* {aka Graph::node_st*}’ to ‘unsigned int’ loses precision [-fpermissive]
Googled and found a similar question but it does not seem to me that the answer is applicable here (note that I want to get the size of the object but not itself).
Thank you in advance for any suggestions!
Upvotes: 1
Views: 5515
Reputation: 206717
The first answer in the SO post you have a link to provides an answer that should work for you.
Use
intptr_t id = ((intptr_t)n - (intptr_t)_nodes) / sizeof(Graph::node);
Upvotes: 1
Reputation: 96241
If n
and _nodes
point to Graph::node
, i.e., they are of type Graph::node *
(which seems to be the case from the error message), and if you wan to calculate the "distance" between the two in terms of the number of Graph::node
elements, you can do:
unsigned int id = n - _nodes;
In C and C++, pointer arithmetic will result in the difference being the number of elements (instead of number of bytes).
For this to work portably, both n
and _nodes
must point to a contiguous block of Graph::node
values, and n
should be "after" _nodes
. If you can get negative differences, you can use ptrdiff_t
type instead of unsigned int
.
Upvotes: 2