在不使用 sizeof 的情況下查詢 C/C++ 中的陣列大小


在此程式中,我們找到在不使用 sizeof 的情況下查詢 C/C++ 中的陣列大小。

演算法

Begin
   Initialize the elements of the array.
   &a => This is the pointer to array which points at the same memory address as a.
   &a + 1 => It points at the address after the end of the array.
   *(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element.
   *(a+1)-a => Subtract the pointer to the first element to get the length of the array.
   Print the size.
End.

示例程式碼

 即時預覽

#include <iostream>
using namespace std;
int main() {
   int a[] = {6,7,5,3,1,4,2,10,9};
   int s = *(&a + 1) - a;
   cout << "Number of elements in array is "<< s;
}

輸出

Number of elements in array is 9

更新於: 30-7-2019

5K+瀏覽

開啟你的 職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.