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

C

C C++ C++

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
 
J

jkherciueh

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
 
E

Erik Wikström

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.
 
S

saurabhsingh6

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;
}
cout<<i; //this will show u the length of array
 
E

Erik Wikström

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;
}
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().
 
C

Christopher Pisz

C C++ 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 ?

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."
 
J

James Kanze

It would help if they said what they meant by dynamic array.
std::vector said:
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":).
 
J

James Kanze

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.


And this is a very noisy way of finding the length, with all
that output.
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.
 
J

jkherciueh

James said:
It would help if they said what they meant by dynamic array.
std::vector said:
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.

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:)

And it certainly wouldn't be a "quick way":).

True.



Best

Kai-Uwe Bux
 
J

Juha Nieminen

Christopher said:
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]).
 
M

Michal Nazarewicz

Erik Wikström 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 ?

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.
 
J

James Kanze

[...]
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 ::eek:perator new() function, rather than new[]. (There
was no ::eek:perator new[]() function at the time. But even today,
the default allocator in the standard uses the ::eek:perator new()
function, and not ::eek:perator 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.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top