Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Calculating Length Of An Array

Calculating Length Of An Array

C Programming Tricks

Calculating length of an array:

Ever wondered why C does not have a built-in operator to get the number of elements in an array? That's because such functionality can be easily implemented by a programmer in a one-line macro:

 /* Returns the number of elements in the array */
 #define NumElm(array) (sizeof (array) / sizeof ((array)[0]))
 

This macro computes the number of elements in an array by dividing the total size of an array by the size of a single element. The most important point to note is that this calculation is done at compile time; this not only makes the use of this macro as efficient at run-time as replacing the macro call with a constant, but also allows the use of the macro call in a context where constant expressions are required, so you can write something like this:

 int a[10];
 int b[NumElm(a)];/* equivalent to int b[10]; */
 

This is a standard way to calculate array length in C; it is described in K&R.

Note that this works only with "real" arrays; the result of this macro when given a pointer as an argument is meaningless (there is no general way to get a number of objects pointed to by a pointer -- pointers to objects and pointers to arrays of objects are the same thing in C. That's a feature.)

Partners