如何在 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