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

P

PengYu.UT

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
 
W

Walter Roberson

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])
 
J

Jens.Toerring

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
 
M

Martin Ambuhl

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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top