C said:
Hi all, got this interview question please respond.
How can you quickly find the number of elements stored in a a) static
array b) dynamic array ?
You do not mention, how the static array and the dynamic array are given to
you. Therefore, I will make some assumptions.
For an array of fixed size, you can use templates:
template < typename T, unsigned long N >
unsigned long length ( T const (&) [N] ) {
return ( N );
}
#include <iostream>
int main ( void ) {
char arr [20];
std::cout << length( arr ) << '\n';
}
On the other hand, there shouldn't be a need for this: you really want to
avoid magic numbers like 20. Thus, you would simply write the code like so:
static const unsigned int my_array_size = 20;
int main ( void ) {
char arr [ my_array_size ];
std::cout << my_array_size << '\n';
}
For an array of T dynamically allocated with new[] and stored in a variable
of type T*, you are simply out of luck: although the compiler has to keep
track of the array size (at least if T has a non-trivial destructor and
there is a corresponding delete[]), there is no way in standard C++ to get
at that piece of information. Thus, you need to store the length manually.
If T is copy-constructible and assignable, you should of course use
std::vector instead. That will keep track of the size for you.
Note: It is possible that one could use some trickery with a user defined
new-handler or some such thing, but I don't know off hand how to do it and
I doubt that it would be a good idea anyway.
Best
Kai-Uwe Bux