问题
我使用简单的cout语句没有输出,而printf总是会输出数字:
std::cout << variableuint8; // prints nothing
printf("%u", variableuint8); // prints the number
我之前从未遇到过这种行为,虽然我有一个解决方法,但我希望理解它。
上下文:
哎呀,指针。因此,情况可能比所述的要复杂一些。这是背景-我认为这并不重要,当cout和printf获取信息时,它被解引用为简单的无符号字符。这可能是解决问题所需的更多信息,但我想尽可能详细地说明,以防它与问题相关。
typedef unsigned char UInt8;
typedef unsigned short UInt16;
typedef struct{
UInt8 len;
// some other definitions. sizeof(DeviceNotification) <= 8
}DeviceNotification;
UInt8 somerandomdata[8];
DeviceNotification * notification;
notification = (DeviceNotification *) somerandomdata;
std::cout << "Len: (" << notification->len << ")\n";
printf("Len: (%u)\n", notification->len);
随机数据已在其他地方初始化。对于这个输出,数组中的第一个字节是0x08:
输出:
Len: ()
Len: (8)
环境
- 开发机器:
- 操作系统: OS X 10.6.8
- 编译器: LLVM 1.7
- Xcode 版本: 3.2.6
- 测试机器:
- 操作系统: OS X 10.6.8
notification = (DeviceNotification *) somerandomdata;
如果对齐不符合DeviceNotification
所需的对齐方式,这行代码难道不会引起未定义的行为吗? - Khaled AlshayaUInt8 len
)是安全的。 - MSalters