Velocity Reviews > How to know the number of elements in an static array.

How to know the number of elements in an static array.

PengYu.UT@gmail.com
Guest
Posts: n/a

 05-20-2005
Hi,

For example, I have the following array. How can I know how many
elements are in the array?

static int space[] = {140, 150, 160, 170, 180, 190, 200, 210, 220, 235,
250,
270, 290, 320, 355, 440, 500, 570, 655, 755, 855, 1025, 1200};

Best wishes,
Peng

Walter Roberson
Guest
Posts: n/a

 05-20-2005
In article <(E-Mail Removed) .com>,
http://www.velocityreviews.com/forums/(E-Mail Removed) <(E-Mail Removed)> wrote:
>For example, I have the following array. How can I know how many
>elements are in the array?

>static int space[] = {140, 150, 160, 170, 180, 190, 200, 210, 220, 235,
>250,
> 270, 290, 320, 355, 440, 500, 570, 655, 755, 855, 1025, 1200};

sizeof(space) / sizeof(space[0])
--
"This was a Golden Age, a time of high adventure, rich living and
hard dying... but nobody thought so." -- Alfred Bester, TSMD

Mick Sharpe
Guest
Posts: n/a

 05-20-2005
Use sizeof(space)/sizeof(int)

Jens.Toerring@physik.fu-berlin.de
Guest
Posts: n/a

 05-20-2005
(E-Mail Removed) <(E-Mail Removed)> wrote:
> For example, I have the following array. How can I know how many
> elements are in the array?

> static int space[] = {140, 150, 160, 170, 180, 190, 200, 210, 220, 235,
> 250,
> 270, 290, 320, 355, 440, 500, 570, 655, 755, 855, 1025, 1200};

sizeof space / sizeof *space

or make a macro out of it:

#defined NUM_ELEMS( x ) ( sizeof x / sizeof x[ 0 ] )

and "NUM_ELEMS( start )" will be an integer (of type size_t) with
the number of elements.

Of course, this requires that 'space' is a real array, not just a
pointer to the first element (to what it would be converted to
when you pass 'space' to a function).

Regards, Jens
--
\ Jens Thoms Toerring ___ http://www.velocityreviews.com/forums/(E-Mail Removed)-berlin.de
\__________________________ http://www.toerring.de

Martin Ambuhl
Guest
Posts: n/a

 05-20-2005
(E-Mail Removed) wrote:
> Hi,
>
> For example, I have the following array. How can I know how many
> elements are in the array?
>
> static int space[] = {140, 150, 160, 170, 180, 190, 200, 210, 220, 235,
> 250,
> 270, 290, 320, 355, 440, 500, 570, 655, 755, 855, 1025, 1200};
>

size_t nelements = sizeof space/sizeof *space;