1

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!

Community
  • 1
  • 1
f10w
  • 1,344
  • 2
  • 21
  • 36

2 Answers2

2

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.

Alok Singhal
  • 88,099
  • 18
  • 124
  • 155
1

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); 
Community
  • 1
  • 1
R Sahu
  • 200,579
  • 13
  • 144
  • 260
  • Hi Sahu. Thanks for the answer. This solution works. However for my case I think @Alok's solution is more elegant. +1 – f10w Aug 26 '14 at 10:09