#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, const char *argv[])
{
vector<bool> a;
a.push_back(false);
int t=a[0];
printf("%d %d\n",a[0],t);
return 0;
}
该代码给出输出“5511088 1”。我以为会是“0 0”。
有人知道为什么吗?
最佳答案
%d
格式说明符用于参数的整数大小,因此printf
函数期望两个参数的大小均等于int
的大小。但是,您为其提供了一个参数,该参数不是int
,而是由vector<bool>
返回的特殊对象,可以转换为bool
。
基本上,这导致printf
函数将堆栈中的随机字节视为值的一部分,而实际上并非如此。
解决方案是将第一个参数转换为int
:
printf("%d %d\n", static_cast<int>(a[0]), t);
更好的解决方案是,如果可能的话,优先使用流而不是
printf
,因为与printf
不同,它们是类型安全的,这使得这种情况不可能发生:cout << a[0] << " " << t << endl;
而且,如果您正在寻找类似
printf
格式的类型安全替代方法,请考虑使用Boost Format库。