Re: How can you quickly find the number of elements stored in a a)
static array b) dynamic array ?
On Jan 12, 3:27 pm, jkherci...@gmx.net wrote:
C C++ C++ wrote:
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 ?
It would help if they said what they meant by dynamic array.
std::vector<>?
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] ) {
Wouldn't size_t be more appropriate as the return type. (It
could matter in the future, when size_t might be an unsigned
long long.)
return ( N );
And of course, the paretheses aren't necessary here.
}
#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';
}
Most of the time, I find it used when you have an initialized
array, with the size determined by the number of initializers.
There are a few cases where I'll go ahead with magic numbers, as
well. If the number is well known, and will never change: I'll
write 12 for the number of months in a year, rather than
defining an explicit constant, for example. But then, of
course, you know the size.
For an array of T dynamically allocated with new[] and stored
in a variable of type T*, you are simply out of luck:
But is there ever, ever a use for such a thing. I've been
programming in C++ for over 15 years now, and I've never used
array new.
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.
And if T isn't copy-constructible and assignable, you're stuck
with an array with all of the elements initialized with the
default constructor, and no way to change the value, if you use
new[]. That doesn't sound very useful either.
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.
And it certainly wouldn't be a "quick way":-).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34