在本章中,我们将研究以下主题:
- 一维数组
- 数组的特征
- 通过指针访问数组元素
- 指针数组
- 将单个数组元素传递给函数
- 将整个数组传递给函数
- 二维数组
数组是相同类型的元素的集合。它是线性和齐次的数据结构。创建数组后,其大小(如果固定)。您不能增加或减少数组的长度。
1.一维数组
一维数组的语法:
<data-type> <variable-name> [ size ];
例:
int arr [20];
数组的初始化:
int arr[5] = {1, 2, 3, 4, 5};
2.数组的特征
- 创建5个整数的数组等于创建5个整数变量。
- 数组元素通过索引访问。
- 数组的索引从0开始。
- 数组的总大小等于数据类型的大小*数组中元素的数量。
将元素存储在数组中并显示它们的简单示例。
#include<iostream> using namespace std; int main() { int arr[5]; cout<<"enter 5 numbers"<<endl; for (int i = 0; i < 5; ++i) // as we are starting the array from 0. { cin>>arr[i]; } cout<<"The entered elements are"<<endl; // here the elements are accessed 上 e by 上 e. cout<<arr[0]<<endl; cout<<arr[1]<<endl; cout<<arr[2]<<endl; cout<<arr[3]<<endl; cout<<arr[4]<<endl; }
输出:
enter 5 numbers 5 4 3 2 1 The entered elements are 5 4 3 2 1
3.通过指针访问数组元素
由于数组存储在连续的内存位置中,因此可以通过指针访问数组元素。
下面是相同的示例:
#include<iostream> using namespace std; int main() { int arr[5] = {1, 2, 3, 4, 5}; int *ptr = NULL; ptr = &arr[0]; // assign the address of first variable of the array to the pointer for (int i = 0; i < 5; ++i) { cout <<" The address of arr["<<i<<"] is = "<< (ptr + i)<<" The value is = "<< *(ptr + i)<<endl; } }
输出:
The address of arr[0] is = 0x7ffeebf53ad0 The value is = 1 The address of arr[1] is = 0x7ffeebf53ad4 The value is = 2 The address of arr[2] is = 0x7ffeebf53ad8 The value is = 3 The address of arr[3] is = 0x7ffeebf53adc The value is = 4 The address of arr[4] is = 0x7ffeebf53ae0 The value is = 5
4.指针数组
数组还可以存储变量的地址。然后它们被称为指针数组。
例:
#include<iostream> using namespace std; int main() { int *arr[3]; int num_1 = 10; int num_2 = 20; int num_3 = 30; arr[0] = &num_1; arr[1] = &num_2; arr[2] = &num_3; for (int i = 0; i < 3; ++i) { cout <<" The address of number ["<<i<<"] is = "<< arr[i] <<" The value is = "<< *arr[i] <<endl; } }
输出:
The address of number [0] is = 0x7ffee0782ab8 The value is = 10 The address of number [1] is = 0x7ffee0782ab4 The value is = 20 The address of number [2] is = 0x7ffee0782ab0 The value is = 30
5.将单个数组元素传递给函数
可以借助该变量的索引将单个元素发送到函数。
例:
#include<iostream> using namespace std; void display(int a); int main() { int arr[3] = {1, 2, 3}; for (int i = 0; i < 3; ++i) { display(arr[i]); } } void display(int a) { cout<<a << endl; }
输出量
1 2 3
6.将整个数组传递给函数
通过发送第一个元素的地址,可以将整个数组传递给函数。
例:
#include<iostream> using namespace std; void display(int arr[] , int length); int main() { int arr[3] = {1, 2, 3}; display(&arr[0], 3); return 0; } void display(int arr[] , int length) { for (int i = 0; i < length; ++i) { cout<<arr[i] << endl; } return; }
输出:
1 2 3
7.二维数组
下图显示了3 * 2、2D阵列的可视化。
下面是显示2D数组的程序:
#include<iostream> using namespace std; int main() { int arr[3] [2] = {1, 2, 3, 4, 5, 6}; for (int row = 0; row < 3; row++) { for (int column = 0; column < 2; column++) { cout<< " "<< arr[row] [column]; } cout<<endl; } }
输出:
1 2 3 4 5 6
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |