-
1 Attachment(s)
Type casting Pointers
Hi everyone,
I learn type casting of pointers.
Could someone explain me why the last printf prints 0.00? I expect to print 10. What I am doing wrong?
Code:
#include <stdio.h>
int main()
{
int a, *Pa;
float b, *Pb;
double c, *Pc;
char d, *Pd;
Pa = &a; // Pa points the address of a
Pb = &b; // Pa points the address of b
Pc = &c; // Pa points the address of b
a = 10;
b = 2.25;
printf("The address of a is %d\n", Pa);
printf("The value of a is %d\n", *Pa);
printf("The address of Pa is %d\n", &Pa);
// What is we want to assign the value of Pa to Pb? Pa is a variable of type int while Pb is a variable of type float
// We have to use type-casting
Pb = (float *)Pa;
printf("The value of b is %.2f\n", *Pb); // Dereferencing Pb to read the value stored in the address the Pb pointer points
return 0;
}
Attachment 16411
-
> What I am doing wrong?
Everything.
> Pb = (float *)Pa;
Just because you made a float pointer point to the bits of an integer, that doesn't make it a valid floating point number when you dereference it.
b = a;
does a proper conversion, and would print 10.0 if you printed b.
If you look at the bits in memory of how an integer 10 and a floating point 10.0 are represented, they look nothing like one another.
-
The representation of the number 10 is different for an integer and a float. Casting to a different type of pointer reinterprets the underlying bytes of the value representation, which does not generally result in the same value.
Code:
#include <stdio.h>
void print_bytes(const void *v, size_t sz)
{
const unsigned char *b = v; // b is a byte pointer
while (sz--) printf("%02x ", (unsigned int)*b++);
printf("\n");
}
int main()
{
int a = 10;
float f = a; // set f to the value of a (modifying the representation to that of a float)
printf("value of a: %d\n", a);
printf("value of f: %.2f\n\n", f);
printf("representation of 10 as int is: ");
print_bytes(&a, sizeof a); // 10 as int is: 0a 00 00 00
printf("representation of 10 as float is: ");
print_bytes(&f, sizeof f); // 10 as float is: 00 00 20 41
printf("\nThe value of a's representation interpreted as a float is %f\n", *(float*)&a);
printf("The value of f's representation interpreted as an int is %d\n", *(int*)&f);
return 0;
}
Output:
value of a: 10
value of f: 10.00
representation of 10 as int is: 0a 00 00 00
representation of 10 as float is: 00 00 20 41
The value of a's representation interpreted as a float is 0.000000
The value of f's representation interpreted as an int is 1092616192
EDIT:
Now I think about it, a float with the representation 0000000A would be a "subnormal" value and not exactly zero. Printing it with 45 decimals yields:
0.000000000000000000000000000000000000000000014
Printing it with the %g spec yields:
1.4013e-44
-