[英]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.