0

Why casting pointer is unsafe if casting for example from long to float

Long var=10; Float*ptr=(floa*)&var;

11th Apr 2019, 10:56 AM
AZ@solo
AZ@solo - avatar
4 Answers
+ 3
Found this nice answer on StackOverflow https://stackoverflow.com/questions/30276645/typecasting-int-pointer-to-float-pointer Casting a value and casting a pointer are different scenarios. Casting a pointer changes the way to refer to the type value, which can almost certainlyresult in a mis-alignment in most of the cases. As per C11 standard document, chapter §6.3.2.3 A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.
11th Apr 2019, 11:50 AM
Louis
Louis - avatar
+ 2
Both are depending on the compiler, but a pointer is the same size no matter what it points to. On most 32 bit compiler a pointer is 4 bytes while on 64 bit they are typically 8 bytes.
11th Apr 2019, 1:14 PM
Rasmus Bons
Rasmus Bons - avatar
+ 1
In general yes. But, It depends on the compiler... I think 🤔 Bcz size of pointer depends on memory size, like 32 bit, 16 bit etc., int size is specific to compiler. Hope this helps....
11th Apr 2019, 1:02 PM
Kuri
Kuri - avatar
0
Louis thanks A lotđź‘Ś I got itđź’Ş Can u tell me is there is a difference between the size of pointer and int? Thanks in advance
11th Apr 2019, 11:58 AM
AZ@solo
AZ@solo - avatar