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

Discussion in 'C Programming' started by PengYu.UT@gmail.com, May 20, 2005.

1. Guest

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

, May 20, 2005

2. Walter RobersonGuest

In article <>,
<> 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

Walter Roberson, May 20, 2005

3. Mick SharpeGuest

Use sizeof(space)/sizeof(int)

Mick Sharpe, May 20, 2005
4. -berlin.deGuest

<> 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 ___ -berlin.de
\__________________________ http://www.toerring.de

-berlin.de, May 20, 2005
5. Martin AmbuhlGuest

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;

Martin Ambuhl, May 20, 2005