一维数组
三种定义方式
数据类型 数组名[数组长度];
数据类型 数组名[数组长度]={值1,值2,值3.......};
数据类型 数组名[ ]={值1,值2,值3.......};
#include <iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
int socore[5] = { 66,35,56,12,88 };
for (int i = 0; i < 5; i++) {
cout << socore[i] << " ";
}
return 0;
}
通过数组名[索引]
来访问数组里的元素,索引从0开始.
数组名命名规范和变量一样,数组名尽量不要和变量重名
数组名的用途
1.可以统计整个数组在内存中的长度
2.可以获取数组在内存中的首地址
#include <iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
int score[5] = { 66,35,56,12,88 };
cout << "数组长度为:" << sizeof(score) << endl;
cout << "数组里的元素数量:" << sizeof(score) / sizeof(score[0]) << endl;
cout << "数组首地址" << score << endl;
return 0;
}
二维数组
- 数据类型 数组名行数;
- 数据类型 数组名行数={{数据1,数据2},{数据3,数据4}};
- 数据类型 数组名行数={数据1,数据2,数据3,数据4};
数据类型 数组名 -{数据1,数据2,数据3,数据4};
建议:以上四种定义方式,利用第二种更加直观,提高代码的可读性#include <iostream> #include<iomanip> #include<cmath> using namespace std; int main() { int arr[2][3] = { {1,2,3},{4,5,6} }; cout << "二维数组总共占用的内存大小:" << sizeof(arr) << endl; cout << "二维数组一行占用的内存大小:" << sizeof(arr[0]) << endl; cout << "二维数组有多少行:" << sizeof(arr) / sizeof(arr[0]) << endl; cout << "二维数组有多少列:" << sizeof(arr[0]) / sizeof(arr[0][0]) << endl; cout << "二维数组首地址" << arr << endl; return 0; }