getting length of an array

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;
}
Where do you get the array from (file, user, in code)?
i just define it in the code
Then you can pre-count it, can't you?
You can calculate the length of the array by doing sizeof(names) / sizeof(*names).
@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.
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
ok thank you.
Topic archived. No new replies allowed.