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}
1// array::size
2#include <iostream>
3#include <array>
4
5int main ()
6{
7 std::array<int,5> myints;
8 std::cout << "size of myints: " << myints.size() << std::endl;
9 std::cout << "sizeof(myints): " << sizeof(myints) << std::endl;
10
11 return 0;
12}
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();