Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: cast from 'void*' to 'int' loses precision

I have a function with prototype void* myFcn(void* arg) which is used as the starting point for a pthread. I need to convert the argument to an int for later use:

int x = (int)arg; 

The compiler (GCC version 4.2.4) returns the error:

file.cpp:233: error: cast from 'void*' to 'int' loses precision 

What is the proper way to cast this?

like image 563
Joshua D. Boyd Avatar asked Oct 28 '09 22:10

Joshua D. Boyd


2 Answers

You can cast it to an intptr_t type. It's an int type guaranteed to be big enough to contain a pointer. Use #include <cstdint> to define it.

like image 65
Ferruccio Avatar answered Sep 19 '22 21:09

Ferruccio


Again, all of the answers above missed the point badly. The OP wanted to convert a pointer value to a int value, instead, most the answers, one way or the other, tried to wrongly convert the content of arg points to to a int value. And, most of these will not even work on gcc4.

The correct answer is, if one does not mind losing data precision,

int x = *((int*)(&arg)); 

This works on GCC4.

The best way is, if one can, do not do such casting, instead, if the same memory address has to be shared for pointer and int (e.g. for saving RAM), use union, and make sure, if the mem address is treated as an int only if you know it was last set as an int.

like image 33
onlooker Avatar answered Sep 23 '22 21:09

onlooker