查找数组长度的一些方法如下:
的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;指针算法可用于查找数组的长度。演示该程序的程序如下。
#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;