如何在 C/C++ 中查找数组的长度?
查找数组长度的一些方法如下所示:
方法 1 - 使用 sizeof 运算符
可以使用 sizeof() 运算符 来查找 数组 的长度。C++ 中使用 sizeof 运算符的示例程序如下所示。
示例
#include <iostream>
using namespace std;
int main() {
int arr[5] = {4, 1, 8, 2, 9};
int len = sizeof(arr)/sizeof(arr[0]);
cout << "The length of the array is: " << len;
return 0;
}以上程序的输出如下:
The length of the array is: 5
现在,让我们了解一下以上程序。
变量 len 存储数组的长度。长度是通过使用 sizeof 获取数组大小,然后将其除以数组一个元素的大小来计算的。然后显示 len 的值。代码片段如下所示:
int arr[5] = {4, 1, 8, 2, 9};
int len = sizeof(arr)/sizeof(arr[0]);
cout << "The length of the array is: " << len;方法 2 - 使用指针
可以使用 指针算术 来查找数组的长度。演示此方法的程序如下所示。
示例
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
cout << "The length of the array is: " << len;
return 0;
}输出
以上程序的输出如下:
The length of the array is: 5
现在,让我们了解一下以上程序。
*(&arr + 1) 中包含的值是数组中 5 个元素之后的地址。arr 中包含的值是数组中起始元素的地址。因此,它们的差值就是数组的长度。代码片段如下所示:
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
cout << "The length of the array is: " << len;
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP