将 int 打印为 float 时 printf 的行为是什么? [英] What is printf's behaviour when printing an int as float?

查看:16
本文介绍了将 int 打印为 float 时 printf 的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 windows7 上使用 dev cpp 来编译我的代码.

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

您会看到,如果我使用 %d 打印 d,它可以打印 e 的 4 个字节.但是如果我像下面这样使用 %f ,它会在必须打印 e 的第一个字节的地方显示零.任何人都可以帮助解决为什么会发生这种情况?为什么e的内容要依赖d的格式?

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();

输出是:

4 4
0028FF40 0028FF40
0028FF40 0028FF40 0028FF41 0028FF42 0028FF43
 0.000000 | 0 | 0 | 0 | 0x28ff40 |76869F1D

推荐答案

未定义的行为.

实际上,您所看到的可能是由于 %f 使 printf 从其参数列表中拉出一个 double,即 8 个字节*.但是 d 的大小只有 4 个字节,所以现在一切都没有对齐.

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.

请记住,printf 是一个可变参数函数,这意味着它是完全非类型安全的;printf 必须在没有编译器帮助的情况下从堆栈中提取原始字节.确保参数与格式字符串精确对应完全取决于您.

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.

<小时>* 可能.

这篇关于将 int 打印为 float 时 printf 的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆