[英]Why is the array not printing out here? (c++)
我的数组是
int age[5] = {11,2,23,4,15}
但它不会打印出11,2,23,4, 15
。
#include <iostream>
#include <array>
using namespace std;
int main() {
int age[5] = {11,2,23,4,15};
cout << age[5] << endl;
}
数组的名称不是age[5]
。
数组的名称是age
。
表达式age[5]
表示数组的第六个元素,该元素不存在。
事实上,没有以格式化方式打印整个数组的内置逻辑,所以即使cout << age << endl
也不正确。
如果要打印数组,请在循环中逐个元素地打印。
Arrays 是 0 索引的。 在您的示例中,有效索引为 0..4。 您正在尝试从age[5]
打印单个int
,这是越界的。
您需要遍历数组的索引,例如:
#include <iostream>
using namespace std;
int main() {
int age[5] = {11,2,23,4,15};
for(int i = 0; i < 5; ++i) {
cout << age[i] << " ";
}
cout << endl;
}
或者:
#include <iostream>
#include <array>
using namespace std;
int main() {
array<int, 5> age{11,2,23,4,15};
for(int val : age) {
cout << val << " ";
}
cout << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.