我知道C ++ 11这样做的方法,但是我被告知要使用"传统的"方式。
无论如何这里是代码:
#include <iostream>
#include <array>
#include <iomanip>
using namespace std;
int main()
{
int items[ 5 ] = {1, 2, 3, 4, 5};
cout << "items before modification: ";
for( unsigned int whatever = 0; whatever < sizeof(items); whatever++ )
{
cout << items[ whatever ] << " ";
}
}
这是输出:
items before modification: 1 2 3 4 5 1 -1073949596 -1073949588 -1073949744 -1217175552 0 0 -1218570461 134514560 0 0 -1218570461 1 -1073949596 -1073949588
我在哪里出错,因为我期待这个输出:
items before modification: 1 2 3 4 5
答案 0 :(得分:4)
sizeof(items)
= no.of items
* size of each item
。您可能想要no. of items only
,因此也将其除以size of each item
。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int items[ 5 ] = {1, 2, 3, 4, 5};
cout << "items before modification: ";
for( unsigned int whatever = 0; whatever < sizeof(items)/sizeof(int); whatever++ )
{
cout << items[ whatever ] << " ";
}
}