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 11 7549
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
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
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
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
"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."
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 orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
On Jan 12, 5:58 pm, Erik Wikström <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 orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
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
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]).
Erik Wikström <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--
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 orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Noah Spitzer-Williams |
last post by:
Hello guys,
I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.
I used to think I could just do: if (arr) ...
However, if...
|
by: nospam |
last post by:
Hi,
I have an application whose textareas rows automatically resize onFocus
to the number of lines in the textArea.
The cols are set to 100% (in a CSS file) in order to always take the
full...
|
by: Herrcho |
last post by:
in K&R Chapter 6.3
it mentions two methods to calculate NKEYS.
and points out the first one which is to terminate the list of
initializers with a null pointer, then loop along keytab until the...
|
by: Vasilis Serghi |
last post by:
Presently I define the number of lines to be expected in a file when
defining the array size and the initialisation of this array. This works
fine for now, but i'm sure that in the future this...
|
by: Massimiliano Alberti |
last post by:
Can someone check this? If it's OK, you can use however you want... :-)
It should search for an element in an array and, if it can't find it, return
the next element.
key is what you are...
|
by: paradox |
last post by:
Basically I have an ArrayList of strings; I need a fast way of
searching through and comparing the elements of the ArrayList and the
return an ArrayList of items that have 3 Duplicates.
For...
|
by: lovecreatesbeauty |
last post by:
/*
How do free() know how many elements should be freed in a dynamic
array?
When free a single variable, the amount of byte of memory can be
retrieved from the type of variable itself.
...
|
by: cnixuser |
last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting...
|
by: arnuld |
last post by:
/* C++ Primer - 4/e
* chapter 4- Arrays & Pointers, exercise 4.28
* STATEMENT
* write a programme to read the standard input and build a vector
of integers from values that are read....
|
by: lllomh |
last post by:
Define the method first
this.state = {
buttonBackgroundColor: 'green',
isBlinking: false, // A new status is added to identify whether the button is blinking or not
}
autoStart=()=>{
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: NeoPa |
last post by:
Hello everyone.
I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report).
I know it can be done by selecting :...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM)
Please note that the UK and Europe revert to winter time on...
|
by: nia12 |
last post by:
Hi there,
I am very new to Access so apologies if any of this is obvious/not clear.
I am creating a data collection tool for health care employees to complete. It consists of a number of...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
| |