How to get the size of an array



In C++ there is no keyword to explictly return the number of elements within an array, however there are a couple of ways to achieve this. The most widely used approach is using the keyword sizeof. This keyword does not return a count of elements, rather the number of bytes the array occupies in memory.

This means the value of sizeof will be greater than the number of elements when using a data type such as int, float, or long due to their size being greater than one byte. To convert the number of bytes to a count of elements we have to divide the result of sizeof by the size of the data type.

void setup(){

  int arr[ 50 ];
  int arrSize = sizeof( arr ) / sizeof( int );
  
  Serial.begin( 9600 );
  Serial.print( arrSize );
}
void loop(){}

The functionality above can be placed into a reuseable macro.

#define arr_len( x )  ( sizeof( x ) / sizeof( *x ) )

void setup(){
  int arr[ 50 ];
  int arrSize = arr_len( arr );
}

When using multi dimensional arrays you need to consider what information you need. As sizeof returns its information relative to a single dimension. To calculate the total number of elements in a multidimensional array you must multiply each dimension together giving a total count.

int arr[2][ 50 ];
int arrSize = arr_len( arr ) * arr_len( arr[ 0 ] );

int arr2[2][2][ 50 ];
int arrSize2 = arr_len( arr2 ) * arr_len( arr2[ 0 ]  ) * arr_len( arr2[0][0] );

 

A more advanced method is using a C++ feature called templates. As this is a topic aimed at new users of Arduino/C++ I provide these methods only for completeness, and as a future reference for users once they are familiar with the required concepts.

The three functions below provide access to dimension counts of up to three dimensions, which can be easily expanded up to any size. This is a valid replacement when macros are undesired.

template< typename T, size_t N > 
	const size_t ArrayLen( T (&)[N] ) 
		{ return N; }
	
template< typename T, size_t A, size_t N > 
	const size_t ArrayLen( T (&)[A][N], const char item = 0x00 ) 
		{ return item ? A : N; }			
	
template< typename T, size_t B, size_t A, size_t N > 
	const size_t ArrayLen( T (&)[B][A][N], const char item = 0x00 ) 
		{ return item ? ( item == 1 ? A : B ) : N; }	

You can calculate array lengths similar to the arr_len macro provided above.

int arr[2][ 50 ];
int arrSize = ArrayLen( arr ) * ArrayLen( arr, 1 );

int arr2[2][2][ 50 ];
int arrSize = ArrayLen( arr2 ) * ArrayLen( arr2, 1 ) * ArrayLen( arr2, 2 );
Tags: array
Last update:
2014-04-01 12:16
Author:
Christopher Andrews
Revision:
1.0
Average rating: 2.6 (10 Votes)

You can comment this FAQ

Chuck Norris has counted to infinity. Twice.