0% found this document useful (0 votes)
19 views3 pages

Array Notes

Uploaded by

taiyamxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views3 pages

Array Notes

Uploaded by

taiyamxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

⼀维数组

1. 如何定义数组

数据类型 数组名[数组⻓度];

int arr[10]; // 定义⼀个⻓度为10的整数数组


double scores[5]; // 定义⼀个⻓度为5的浮点数数组

2. 如何使⽤数组

数组名[索引];

int arr[5] = {1, 2, 3, 4, 5};


cout << arr[2]; // 输出3

int arr[5] = {1, 2, 3, 4, 5};


cout << arr[2]; // 输出3

3. 数组在内存中的存储

数组中的元素在内存中连续存储
数组名实际上是⼀个常量指针,指向数组的第⼀个元素
数组的索引就是偏移量,例如 arr[2] 表⽰数组的第3个元素,其地址为 arr + 2 * sizeof(int)。

4. 数组的赋值和初始化

初始化:
在定义时初始化:int arr[5] = {1, 2, 3, 4, 5};
部分初始化:int arr[5] = {1, 2};,剩余元素会被初始化为0。

赋值:

arr[0] = 10; // 给第⼀个元素赋值

#include <iostream>

using namespace std;

int main() {

PROFESSEUR : M.DA ROS BTS SIO BORDEAUX - LYCÉE GUSTAVE EIFFEL


✦1/3✦
int arr[5] = {1, 2, 3, 4, 5};

// 数组名作为指针使⽤
int *ptr = arr; // ptr指向数组arr的第⼀个元素
cout << *ptr << endl; // 输出第⼀个元素的值

// 遍历数组
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << " "; // 使⽤指针访问数组元素
}
cout << endl;

// 修改数组元素
*(ptr + 2) = 10; // 将第三个元素的值改为10
cout << arr[2] << endl; // 输出修改后的第三个元素

// 数组名不能修改
// arr = arr + 1; // 错误,数组名是常量指针

return 0;
}

⼆维数组
1. 如何定义和使⽤⼆维数组

数据类型 数组名[⾏数][列数];

int matrix[3][4]; // 定义⼀个3⾏4列的⼆维数组

matrix[1][2] = 5; // 访问第⼆⾏第三列的元素

#include <iostream>

using namespace std;

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// 访问元素
cout << arr[2] << endl;
cout << matrix[1][2] << endl;

// 遍历数组

PROFESSEUR : M.DA ROS BTS SIO BORDEAUX - LYCÉE GUSTAVE EIFFEL


✦2/3✦
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;

// 使⽤指针
int *ptr = arr;
cout << *ptr << endl; // 输出第⼀个元素

return 0;
}

#include <iostream>

using namespace std;

int main() {
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// 数组名作为指针使⽤
int (*ptr)[4] = arr; // ptr指向⼀个包含4个整数的⼀维数组

// 遍历⼆维数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << *(*(ptr + i) + j) << " ";
}
cout << endl;
}

// 修改元素
*(*(ptr + 1) + 2) = 20; // 将第⼆⾏第三列的元素改为20

// 输出修改后的数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}

return 0;
}

PROFESSEUR : M.DA ROS BTS SIO BORDEAUX - LYCÉE GUSTAVE EIFFEL


✦3/3✦

You might also like