Difference between revisions of "Compute the number of elements in an array"

From CodeCodex

m (reworded the note)
(C/C++: added description, reworded note again)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 
===C/C++===
 
===C/C++===
 +
The trick to computing the number of elements in an array is to divide the total size of an array by the size of a given element. For example, if the total size of the array is 80 bytes and each element takes up 8 bytes, there must be 10 elements in the array.
 
<pre>
 
<pre>
 
sizeof(array) / sizeof(array[0]);
 
sizeof(array) / sizeof(array[0]);
Line 8: Line 9:
 
#define NumElm(array) (sizeof(array) / sizeof((array)[0]))
 
#define NumElm(array) (sizeof(array) / sizeof((array)[0]))
 
</pre>
 
</pre>
<b>Note</b>: the result will be off by +1 on arrays that are either null- or zero-terminated (including strings).
+
<b>Note</b>: this method will not work for arrays that are zero- or null-terminated (including strings).
  
 
===Java===
 
===Java===

Revision as of 10:17, 3 July 2008

Implementations

C/C++

The trick to computing the number of elements in an array is to divide the total size of an array by the size of a given element. For example, if the total size of the array is 80 bytes and each element takes up 8 bytes, there must be 10 elements in the array.

sizeof(array) / sizeof(array[0]);

Ideally, you would put this into a macro as follows:

#define NumElm(array) (sizeof(array) / sizeof((array)[0]))

Note: this method will not work for arrays that are zero- or null-terminated (including strings).

Java

int[] myArray;
myArray.length();