insane C program needing explanation

Status
Not open for further replies.

blackleopard92

In the zone
does anybody have any idea what's going on here?

#include <stdio.h>

int main()
{
float a = 65.375;
char *p;
int i;

p = (char*)&a;
printf("%c\n",*p);

for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
printf("\n");

printf("\n");

return 0;
}
 

Hulo

Broken In
Quite meaningless in fact. If we simplify it to the following, we'd get the same result. But this is more comprehensible:

#include <stdio.h>

int main()
{
float a = 65.375;
char *p;
int i;

p = &a;
for(i=0;i<=3;i++)
printf("%x",(char)p);
printf("\n");
return 0;
}

p holds the address of a, which is an integer. That integer is typecasted to char, which is printed out by formatting it as an unsigned hex. Output is 4c. The loop prints it four times, so the output is 4c4c4c4c. The original program does the same with some unnecessary assignments in-between which has no effect on the ultimate output.
 
Last edited:

mehulved

18 Till I Die............
I get the answer as x8x8x8x8, where x is any hex. number. Is that anything to do with compilers?
 

Hulo

Broken In
Yes. Because &a , the address, would vary. Even in the same compiler it could vary on different instances. I ran it on VC++ in Visual Studio 2005.
 
OP
blackleopard92

blackleopard92

In the zone
Hulo said:
p holds the address of a, which is an integer. That integer is typecasted to char, which is printed out by formatting it as an unsigned hex. Output is 4c. The loop prints it four times, so the output is 4c4c4c4c. The original program does the same with some unnecessary assignments in-between which has no effect on the ultimate output.
a is a float.and if i am correct, floats are stored differently than integers.
but i get the idea though
 

Hulo

Broken In
That's correct but &a extracts the beginning address of the location from where the storage begins. And that address is always an integer.

There is a thing that I forgot to mention. Here p is a character pointer. So when we assign the address to p, it points to the first byte only. Had it been an integer pointer, it would have pointed to the first byte of the 2 consecutive bytes of storage (assuming that in this compiler int is stored in 2 bytes and char in 1).

Thus, strictly speaking, the assignment p = (char*)&a is necessary if we had done some pointer arithmatic after this e.g. p+2 where p is a char pointer and p+2 where p is an integer pointer would not have been the same. In this case however there is no pointer arithmatic. So the results are coming as same.
 
Status
Not open for further replies.
Top Bottom