DIGIT-ARC read-only archive · snapshot: July 23, 2026

insane C program needing explanation

6 posts · originally from https://geek.digit.in/community/threads/insane-c-program-needing-explanation.60630/

blackleopard92
blackleopard92 Original post #1
Jun 17, 2007 at 1:14 PM
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
Hulo #2
Jun 17, 2007 at 8:19 PM
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.
M
Jun 17, 2007 at 8:41 PM
I get the answer as x8x8x8x8, where x is any hex. number. Is that anything to do with compilers?
Hulo
Hulo #4
Jun 18, 2007 at 12:15 AM
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.
blackleopard92
Jun 18, 2007 at 12:17 AM
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
Hulo #6
Jun 18, 2007 at 12:33 AM
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.