A quick way to determine array size using sizeof is known as: sizeof(array)/sizeof(*array)

for example:

#include<iostream>
using namespace std;
int main(){
    int A[5] = {1,2,3,4,5};
    cout<<sizeof(A)/sizeof(*A)<<endl;
    return 0;
}

The output is 5.

However, if passing an array to a function:

#include<iostream>
using namespace std;
int getLength(int A[]){
    return sizeof(A)/sizeof(*A); 
}
int main(){
    int A[5] = {1,2,3,4,5};
    cout<<getLength(A)<<endl;
    return 0;
}

The output is 1 since in the call of getLength(A), the array is actually be passed as a pointer.

Refering [1] and [2], to preserve the array type, we should pass in a reference to the array. I prefer the solution mentioned in [2]:

#include<iostream>
using namespace std;
// A is a reference to an array of N T type data
template<typename T, int N>
int getLength(T (&A)[N]){
    return sizeof(A)/sizeof(*A); 
}
int main(){
    int A[5] = {1,2,3,4,5};
    cout<<getLength(A)<<endl;
    return 0;
}

The output is 5.

References:

  1. Sizeof array passed as parameter
  2. determine size of array if passed to function

Yang Song

Ph.D. Student in Robotics