Why casting pointer is unsafe if casting for example from long to float | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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