CH05_数组
概述
定义:一组相同类型的数据的集合。
描述:
1.数组中的每个元素都是相同的数据类型
2.数组是由连续的内存位置组成的。
3.数组索引是从0开始
一维数组
语法:
1.数据类型 数组名[长度];
2.数据类型 数组名[长度]={值1,值2,值3…};
3.数据类型 数组名[]={值1,值2,值3…};
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> using namespace std;
int main() {
int nums1[5]; nums1[0] = 23; nums1[1] = 17; nums1[2] = 35;
int nums2[5] = { 12,35,100 };
int nums3[]= { 12,35,100 };
cout << nums2[4] << endl;
int length = sizeof(nums2) / sizeof(nums2[0]); for (int i = 0; i < length; i++) { cout << nums2[i] << endl; } cout << "数组首地址为:" << (int)nums2 << endl; cout << "数组中第一个元素地址为:" << (int)&nums2[0] << endl; cout << "数组中第二个元素地址为:" << (int)&nums2[1] << endl;
system("pause"); return 0; }
|
二维数组
语法:
1 2 3 4 5 6 7
| 数据类型 数组名[行数][列数];
数据类型 数组名[行数][列数]={{值1,值2},{值3,值4}};
数据类型 数组名[行数][列数]={值1,值2,值3,值4};
数据类型 数组名[ ][列数]={值1,值2,值3,值4};
|
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <iostream> using namespace std;
int main() {
int arr1[2][3]; arr1[0][0] = 11; arr1[0][1] = 12; arr1[0][2] = 13; arr1[1][0] = 14; arr1[1][1] = 15; arr1[1][2] = 16;
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr1[i][j] <<"\t"; } cout << endl; }
cout << "-------------------" << endl;
int arr2[2][3] = { {12,25,33}, {13,26,27} };
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr2[i][j]<<"\t"; } cout << endl; } cout << "-------------------" << endl;
int arr3[2][3] = {1,2,3,4,5,6};
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr3[i][j] << "\t"; } cout << endl; } cout << "-------------------" << endl;
int arr4[][3] = { 1,2,3,4,5,6,7,8 };
int row = (sizeof(arr4) / sizeof(int)) / (sizeof(arr4[0]) / sizeof(int)); for (int i = 0; i < row; i++) { for (int j = 0; j < 3; j++) { cout << arr4[i][j] << "\t"; } cout << endl; } cout << "-------------------" << endl;
cout << "数组首地址:" << (int)arr4 << endl; cout << "数组第一行第一列:" << (int)&arr4[0][0] << endl; cout << "数组第一行第二列:" << (int)&arr4[0][1] << endl; cout << "数组第二行第一列:" << (int)&arr4[1][0] << endl;
system("pause"); return 0; }
|