+ 4
Why it gives segfault?
#include <iostream> int main(){ int a{45}; double* pd=reinterpret_cast<double*>(a); std::cout<<*pd<<std::endl; return 0; }
16 Respuestas
+ 8
I guess you are not allowed to access memory address 45.
Perhaps you meant to reinterpret the value 45 as a double. To fix it, replace (a) with (&a).
+ 6
Also, note that you have a buffer overflow error and you should use `long` for `a` to be the same size as `double`. Otherwise it uses extra random data nearby (in stack) and gives different results for each run.
+ 4
reinterpret_cast is undefined territory and should be avoided.
Good to know.
But even better to understand the reason to not use it unless absolutely necessary.
https://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast
nice discussion with lots of examples.
+ 3
Ujjawal Gupta
Ok got it
Keep that curiosity up on fire : )
+ 2
Why go through all these to have a `double` value from `int` value? what is your plan?
I'm sure you know these types has incompatibilities, and that inter-type casting *may* introduce a flaw (can't expect reliability on precision)
+ 2
Ipang ikr, casting is an ugly and dangerous operation, but actually I wants to learn how reinterpret_cast works
+ 2
Ipang no, there's no such type. Maybe they meant "a float with no sign", i. e. non-negative?
+ 2
Евгений
Yes also IIRC signedness modifier `unsigned` is only for integral types. I find it hard to believe nobody noticed that, in a strict place like stackoverflow ...
+ 2
I edited the answer at stackoverflow, now there's no "unsigned float" nonsense.
+ 1
Brian I think it has to do something with bit level representation of int and double 🤔
+ 1
Ipang sure :)
+ 1
Bob_Li gotcha
+ 1
Bob_Li
I can't help to wonder if it is true there is `unsigned float` type as someone mentioned in one of the answers in the thread you attached ...
https://stackoverflow.com/a/43273907
"When you convert for example int(12) to unsigned float (12.0f) your processor needs to invoke some calculations as both numbers has different bit representation ..."
Is there really `unsigned float` type?
+ 1
Ipang
unsigned float... I didn't notice that, too.😁 Good catch. I never wondered about why there is no unsigned float or double. Now I know.
https://stackoverflow.com/questions/2523025/unsigned-double-in-c
+ 1
Thanks for the edit Евгений
From now on people who follows up on that thread in stackoverflow (and this one here) are saved from a misunderstanding possibly arised from the `unsigned float` typo : )
0
Евгений Roger that