What Actually this line of code `ptr=(char *)&a;` does?
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++
incre开发者_如何学Cments? 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 a float*
; casting that to a char*
gives you a pointer referring to the same location in memory, but pretending that what lives there is char
data rather than float
data.
sizeof(float)
is 4
, 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 as signed char
and then converted to int
for display, they appear as negative values on account of their two's-complement representation.
The expression *ptr++
is equivalent to *(ptr++)
, which first increments ptr
then dereferences its previous value; you can think of it as simultaneously dereferencing and advancing ptr
.
That line casts the address of a
, denoted &a
, to a char*
, i.e. a pointer to characters/bytes. The printf
loop then prints the values of the four constituent bytes of a
in decimal.
(Btw., it would have been neater if the loop had been
for (i=0; i<sizeof(a); i++)
printf("%d ", ptr[i]);
)
The line ptr=(char *)&a;
casts the address of the float
variable to a pointer of type char
. Thus you are now interpreting the 4 bytes of which the float consists of as single bytes, which values you print with your for
loop.
The statement *ptr++
post-increments the pointer after reading its value, which means, you read the value pointed to (the single bytes of the float) and then advance the pointer by the offset of one byte.
&a
gets the address of a
, that is, it yields a pointer of type float *
. This pointer of type float *
is then cast to a pointer of type char *
.
Because sizeof(char) == 1
, a
can now be seen through ptr
as a sequence of bytes.
This is useful when you want to abstract away the type of a variable and treat it as a finite sequence of bytes, especially applicable in serialisation and hashing.
精彩评论