1#include <iostream>
2using namespace std;
3
4#define size(type) ((char *)(&type+1)-(char*)(&type))
5
6int main(){
7 int arr[5] = {1, 2, 3, 4, 5};
8 cout << size(arr) / size(arr[0]) << endl; //returns 5
9 //alternatively
10 cout << sizeof(arr) / sizeof(int) << endl; //returns 5
11}
1#include <iostream>
2using namespace std;
3int main() {
4 int arr[5] = {4, 1, 8, 2, 9};
5 int len = sizeof(arr)/sizeof(arr[0]);
6 cout << "The length of the array is: " << len;
7 return 0;
8}
1How do I find the length of an array?
2//Method 1:
3- use sizeof(arr)/sizeof(*arr)
4
5//Method 2:
6- use std::array from C++11
7array <int,6> arr{1, 2, 3, 4, 5, 6};
8cout << arr.size();