getting length of an array

Sep 6, 2012 at 3:46pm
i have an array and i should like to get the length of the array (in other words how many values the array has) can someone tell me a function or something that helps me doing this.

the array names normally contains more then 5000 values and i need to know how many exactly

this is my code:
1
2
3
4
5
6
7
8
9
int main() {
	clock_t start, end;
	start = clock();
	string names[]={"MARY","MARCELLUS","LUCIUS","KRISTOFER","BOYCE","BENTON","HAYDEN","HARLAND","ARNOLDO","RUEBEN","LEANDRO","KRAIG","JERRELL","JEROMY","HOBERT","CEDRICK","ARLIE","WINFORD","WALLY","LUIGI","KENETH","JACINTO","GRAIG","FRANKLYN","EDMUNDO","SID","PORTER","LEIF","JERAMY","BUCK","WILLIAN","VINCENZO","SHON","LYNWOOD","JERE","HAI","ELDEN","DORSEY","DARELL","BRODERICK","ALONSO"};
	end = clock();
	printf("\nTook %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);
	system("pause");
	return 0;
}
Sep 6, 2012 at 3:50pm
Where do you get the array from (file, user, in code)?
Sep 6, 2012 at 3:54pm
i just define it in the code
Sep 6, 2012 at 3:55pm
Then you can pre-count it, can't you?
Sep 6, 2012 at 3:57pm
You can calculate the length of the array by doing sizeof(names) / sizeof(*names).
Sep 6, 2012 at 3:59pm
@peter: if i do that i get the total amount of characters. that is not what i want. i want the total amount of names.
Sep 6, 2012 at 4:02pm
No, you get the number of std::strings in the array.

You can also define a function using templates.
1
2
3
4
5
template <typename T, std::size_t N>
std::size_t getArrayLength(T (&)[N])
{
	return N;
}
This is a bit more safe because it gives you an error if what you try to pass to it is not an array.
Last edited on Sep 6, 2012 at 4:18pm
Sep 6, 2012 at 4:08pm
ok thank you.
Topic archived. No new replies allowed.