By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,742 Members | 2,044 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,742 IT Pros & Developers. It's quick & easy.

How can you quickly find the number of elements stored in a a) staticarray b) dynamic array ?

P: n/a
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 ?

Rgrds
MA
Jan 12 '08 #1
Share this Question
Share on Google+
11 Replies


P: n/a
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 ?
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
Jan 12 '08 #2

P: n/a
On 2008-01-12 15:05, 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 ?
The simple answer to both is to check the variable containing the size.
More involved answer: The size of a statically allocated array must be
known at compile-time so the size is always known. You can use a
construct like this to get its size:

int a[5];
std::cout << sizeof(a) / sizeof(int);

For a dynamically allocated array all you have is a pointer to the first
element, if you do not use some special element at the end of the array
you can not determine the size, this means that you have to pass the
size along with the pointer to the first element.

Note also that unless you use some template tricks a statically
allocated arrays decays into a pointer to its first element when passed
to a function, which means that you are in the same situation as with a
dynamically allocated array: you need to pass the size or have a special
terminating element.

Of course when asked such a question you should ask the questioner why
they did not use std::vector or similar instead of using a raw array.

--
Erik Wikström
Jan 12 '08 #3

P: n/a
On Jan 12, 7:05 pm, "C C++ C++" <m.azm...@gmail.comwrote:
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 ?

Rgrds
MA
say if the array named a[]
then
for(i=0;i!='\0';i++)
{
cout<<a[i];
}
cout<<i; //this will show u the length of array
Jan 12 '08 #4

P: n/a
On 2008-01-12 17:36, sa***********@gmail.com wrote:
On Jan 12, 7:05 pm, "C C++ C++" <m.azm...@gmail.comwrote:
>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 ?

Rgrds
MA

say if the array named a[]
then
for(i=0;i!='\0';i++)
{
cout<<a[i];
}
cout<<i; //this will show u the length of array
Most definitely will not! It will only work for a null-terminated char
array, and that is all. But if that is what you have then you are better
of using strlen().

--
Erik Wikström
Jan 12 '08 #5

P: n/a

"C C++ C++" <m.******@gmail.comwrote in message
news:65**********************************@e4g2000h sg.googlegroups.com...
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 ?

Rgrds
MA
Silly interview questions. Who asked you that out of curiosity?
I probably would of answered, "You can't unless the size was stored in a
seperate variable somewhere." To make my self look good and not leave a
"could no answer" check mark on thier interview sheet, I would elaborate,
"However, I would not use either in code. I would use an STL container, all
of which have a size() method. Which one would depend on its use and
purpose."
Jan 12 '08 #6

P: n/a
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:ja*********@gmail.com
Conseils en informatique oriente objet/
Beratung in objektorientierter Datenverarbeitung
9 place Smard, 78210 St.-Cyr-l'cole, France, +33 (0)1 30 23 00 34
Jan 12 '08 #7

P: n/a
On Jan 12, 5:58 pm, Erik Wikstrm <Erik-wikst...@telia.comwrote:
On 2008-01-12 17:36, saurabhsin...@gmail.com wrote:
On Jan 12, 7:05 pm, "C C++ C++" <m.azm...@gmail.comwrote:
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 ?
say if the array named a[]
then
for(i=0;i!='\0';i++)
I presume that this is a typo for:
for ( i = 0 ; a[ i ] != '\0' ; i ++ )

As written, the loop will never execute.
{
cout<<a[i];
And this is a very noisy way of finding the length, with all
that output.
}
cout<<i; //this will show u the length of array
Most definitely will not! It will only work for a
null-terminated char array, and that is all.
Not even then. It will give you the length of the string
currently in the array, not the size of the array.
But if that is what you have then you are better
of using strlen().
The problem is, of course, that not all arrays have char as the
base type, that even those that do don't necessarily contain
nul terminated strings, and that even then, the length of the
string is not necessarily the length of the array.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique oriente objet/
Beratung in objektorientierter Datenverarbeitung
9 place Smard, 78210 St.-Cyr-l'cole, France, +33 (0)1 30 23 00 34
Jan 12 '08 #8

P: n/a
James Kanze wrote:
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.)
Yes, std::size_t would be better.

> return ( N );

And of course, the paretheses aren't necessary here.
Not necessary, but I prefer them. I also write

delete ( ptr );

knowing that the parentheses are not necessary. However, I do not want to
get into yet another futile discussion on style and taste; so I will not
provide any rationale for my preference.

> }
> #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.
I did: many of my classes are container-like. Ok, strictly speaking, I also
never new[] an array since the classes are all templated on an allocator.

>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.
Well, it could be a type that implements only one of the two concepts. (Not
that I know why one would do that:-)

>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":-).
True.

Best

Kai-Uwe Bux
Jan 12 '08 #9

P: n/a
Christopher Pisz wrote:
I probably would of answered, "You can't unless the size was stored in a
seperate variable somewhere."
That's true for the dynamic array but not the static one because for
static arrays you can obviously do a sizeof(array)/sizeof(array[0]).
Jan 13 '08 #10

P: n/a
Erik Wikstrm <Er***********@telia.comwrites:
On 2008-01-12 15:05, 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 ?

The simple answer to both is to check the variable containing the size.
More involved answer: The size of a statically allocated array must be
known at compile-time so the size is always known. You can use a
construct like this to get its size:

int a[5];
std::cout << sizeof(a) / sizeof(int);
`sizeof a / sizeof *a` is better since it will work after one changes
array's type to (say) long long.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--
Jan 16 '08 #11

P: n/a
On Jan 12, 7:24 pm, jkherci...@gmx.net wrote:
James Kanze wrote:
On Jan 12, 3:27 pm, jkherci...@gmx.net wrote:
C C++ C++ wrote:
[...]
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.
I did: many of my classes are container-like. Ok, strictly
speaking, I also never new[] an array since the classes are
all templated on an allocator.
Exactly. Even 15 years ago, before I'd ever heard of
allocators, and was still simulating templates with <generic.h>,
I never used a raw dynamically allocated [], and all of my
containers separated allocation and construction, so that I
could pre-allocate (like std::vector). Which meant that they
used the ::operator new() function, rather than new[]. (There
was no ::operator new[]() function at the time. But even today,
the default allocator in the standard uses the ::operator new()
function, and not ::operator 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.
Well, it could be a type that implements only one of the two
concepts. (Not that I know why one would do that:-)
There's always the possibility that the default constructor
accesses some static variable, and updates it. But that's
something I definitly wouldn't recommend.

In the end, using container classes is the only way to go. And
said container classes should use the solution adopted by
std::vector---which was estabilished "best practice" long before
the STL was invented. (On the other hand, the work on the STL
provided the impetus for member templates, and member templates
definitely make the solution more agreeable.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique oriente objet/
Beratung in objektorientierter Datenverarbeitung
9 place Smard, 78210 St.-Cyr-l'cole, France, +33 (0)1 30 23 00 34
Jan 17 '08 #12

This discussion thread is closed

Replies have been disabled for this discussion.