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

查看:24
本文介绍了将 int 打印为浮点数时 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,它会很好地打印 4 个字节的 e.但是,如果我像下面这样使用 %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 打印为浮点数时 printf 的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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