how to find array size in c++ code example

Example 1: c++ get length of array

int arr[5];
int len = sizeof(arr) / sizeof(arr[0]);
// returns 5

Example 2: array length c++

#include <iostream>
using namespace std;

#define size(type) ((char *)(&type+1)-(char*)(&type))

int main(){
  int arr[5] = {1, 2, 3, 4, 5};
  cout << size(arr) / size(arr[0]) << endl; //returns 5
  //alternatively
  cout << sizeof(arr) / sizeof(int) << endl; //returns 5
}

Example 3: length of array c++

// array::size
#include <iostream>
#include <array>

int main ()
{
  std::array<int,5> myints;
  std::cout << "size of myints: " << myints.size() << std::endl;
  std::cout << "sizeof(myints): " << sizeof(myints) << std::endl;

  return 0;
}

Example 4: how to get size of array c++

How do I find the length of an array?
//Method 1:
- use sizeof(arr)/sizeof(*arr) 

//Method 2: 
- use std::array from  C++11
array <int,6> arr{1, 2, 3, 4, 5, 6}; 
cout << arr.size();

Tags:

Java Example