在打印一个int浮动时,什么是printf的行为? [英] What is printf's behaviour when printing an int as float?

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

问题描述

我使用的Windows7上开发CPP编译我的code。

  INT D = 0×12;
字符* E =(字符*)和D;
的printf(%D \\ N的sizeof(INT)的sizeof(浮动));
的printf(%P%P \\ N,和D,(浮点*)和D);
的printf(%P%P%P%P%P \\ N,和D,急症室的[0],急症室的[1],急症室的[2],急症室的[3]);
的printf(%d个|%X |%#1X |%#1X |%#1X |%P \\ N,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个字节电子罚款。但是,如果使用%F象下面,它显示了在地方零,其中e的第一个字节必须被打印。任何人都可以用,为什么出现这种情况帮助吗?为什么要ê的内容取决于d为如何格式化?

  INT D = 0×12;
字符* E =(字符*)和D;
的printf(%D \\ N的sizeof(INT)的sizeof(浮动));
的printf(%P%P \\ N,和D,(浮点*)和D);
的printf(%P%P%P%P%P \\ N,和D,急症室的[0],急症室的[1],急症室的[2],急症室的[3]);
的printf(%F |%X |%#1X |%#1X |%#1X |%P \\ N,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 从参数列表,这是8个字​​节双 * 。但 D 的大小只有4个字节,所以现在一切都对齐。

记住的printf 是一个可变参数函数,这意味着它是完全非类型安全的; 的printf 已提取栈原始字节没有从编译器的帮助。这完全取决于你保证参数pcisely对应$ P $格式字符串。



<子> *也许吧。

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

int d = 0x12;
char* e = (char*)&d;
printf("%d %d\n", sizeof (int), sizeof (float));
printf("%p %p\n", &d, (float*)&d);
printf("%p %p %p %p %p\n", &d, &e[0], &e[1], &e[2], &e[3]);
printf(" %d | %x | %#1x | %#1x | %#1x |%p\n", 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\n", sizeof (int), sizeof (float));
printf("%p %p\n", &d, (float*)&d);
printf("%p %p %p %p %p\n", &d, &e[0], &e[1], &e[2], &e[3]);
printf(" %f | %x | %#1x | %#1x | %#1x |%p\n", 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

解决方案

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.

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

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