我知道 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
最佳答案
sizeof(items)
= 项目数量
* 每个项目的大小
。您可能想要不。仅包含项目
,因此也将其除以每个项目的大小
。
#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 ] << " ";
}
}
关于c++ - 需要有关使用 for 循环显示我的数组的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921399/