Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c - What is printf's behaviour when printing an int as float?

I am using dev cpp on windows7 to compile my code.

int d = 0x12;
char* e = (char*)&d;
printf("%d %d
", sizeof (int), sizeof (float));
printf("%p %p
", &d, (float*)&d);
printf("%p %p %p %p %p
", &d, &e[0], &e[1], &e[2], &e[3]);
printf(" %d | %x | %#1x | %#1x | %#1x |%p
", d,  e[0], e[1], e[2], e[3], &e[0]);
getchar();

4 4 
0028FF40 0028FF40
0028FF40 0028FF40 0028FF41 0028FF42 0028FF43  
18 | 12 | 0 | 0 | 0 |0028FF40

You an see that if I use %d for printing d, it is printing the 4 bytes of e fine. But if I use %f like below, it shows zeros in the place where the first byte of e have to be printed. Anyone can help with why this happens? Why should e's contents depend on how d is formatted?

int d = 0x12;
char* e = (char*)&d;
printf("%d %d
", sizeof (int), sizeof (float));
printf("%p %p
", &d, (float*)&d);
printf("%p %p %p %p %p
", &d, &e[0], &e[1], &e[2], &e[3]);
printf(" %f | %x | %#1x | %#1x | %#1x |%p
", d,  e[0], e[1], e[2], e[3], &e[0]);
getchar();

The output is:

4 4
0028FF40 0028FF40
0028FF40 0028FF40 0028FF41 0028FF42 0028FF43
 0.000000 | 0 | 0 | 0 | 0x28ff40 |76869F1D
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Undefined behaviour.

In practice, what you're seeing is probably due to the fact that %f makes printf pull a double from its argument list, which is 8 bytes*. But d is only 4 bytes in size, so now everything is misaligned.

Remember that printf is a variadic function, which means it's completely non-type-safe; printf has to extract raw bytes from the stack without any help from the compiler. It's entirely up to you to ensure that the arguments correspond precisely to the format string.


* Probably.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...