Dave's Brain

Browse - Programming Tips - How can I programmatically see how many elements are in an array?

Date: 2013may7
Level: beginner
Language: C/C++

Q.  How can I programmatically see how many elements are in an array?

A.  If you have:

int a[10];
You can do:
nElements = sizeof(a) / sizeof(a[0]);
This is a nice idiom. Its better than:
#define N_ELEMENTS (45)
int a[N_ELEMENTS];
nElements = N_ELEMENTS; // Not 100% sure that N_ELEMENTS was use to declare a (in a big program)
In Java you can just do:
a.length

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.