CH05_數組
概述
定義:一組相同類型的數據的集合。
描述:
1.數組中的每個元素都是相同的數據類型
2.數組是由連續的內存位置組成的。
3.數組索引是從0開始
一維數組
語法:
1.數據類型 數組名[長度];
2.數據類型 數組名[長度]={值1,值2,值3...};
3.數據類型 數組名[]={值1,值2,值3...};
示例:
#include <iostream>
using namespace std;
int main() {
//方式1
int nums1[5];
nums1[0] = 23;
nums1[1] = 17;
nums1[2] = 35;
//方式2
int nums2[5] = { 12,35,100 };
//方式3
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}};
數據類型 數組名[行數][列數]={值1,值2,值3,值4};
數據類型 數組名[ ][列數]={值1,值2,值3,值4};
示例:
#include <iostream>
using namespace std;
int main() {
//方式1.數據類型 數組名[行數][列數];
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;
//方式2.數據類型 數組名[行數][列數] = { {值1,值2},{值3,值4} };
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;
//方式3.數據類型 數組名[行數][列數] = { 值1,值2,值3,值4 };
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;
//方式4.數據類型 數組名[][列數] = { 值1,值2,值3,值4 };
int arr4[][3] = { 1,2,3,4,5,6,7,8 };//自動計算行數
//數組行數:(sizeof(a) / sizeof(int)) / (sizeof(a[0]) / sizeof(int))
//數組列數:(sizeof(a[0]) / sizeof(int))
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;
}
浙公網安備 33010602011771號