I have the code :
#include<stdio.h>
void main(){
int i;
float a=5.2;
char *ptr;
ptr=(char *)&a;
for(i=0;i<=3;i++)
printf("%d ",*ptr++);
}
I got the output as 102 102 -90 64. I couldn’t predict how it came, I get confused with this line ptr=(char *)&a;. Can anyone explain me what it does? And as like other variables the code *ptr++ increments? Or there is any other rule for pointers with this case.
I’m a novice in C, so explain the answer in simple terms. Thanks in advance.
This is called a cast. In C, a cast lets you convert or reinterpret a value from one type to another. When you take the address of the
float, you get afloat*; casting that to achar*gives you a pointer referring to the same location in memory, but pretending that what lives there ischardata rather thanfloatdata.sizeof(float)is4, so printing four bytes starting from that location gives you the bytes that make up the float, according to IEEE-754 single-precision format. Some of the bytes have their high bits set, so when interpreted assigned charand then converted tointfor display, they appear as negative values on account of their two’s-complement representation.The expression
*ptr++is equivalent to*(ptr++), which first incrementsptrthen dereferences its previous value; you can think of it as simultaneously dereferencing and advancingptr.