Re: Array Dimensions : arrayLength()???
On Feb 15, 10:44 am, Ulrich Eckhardt <ulrich.eckha...@dominolaser.com>
wrote:
TheGunslinger wrote:
Is there a builtin function that returns the dimensions of an array?
No. You can take the size of the array and divide it by the size of each
array element instead.
char characterArray[20];
//-----------------------------------------------------
int arrayLength = dimension(characterArray);
//returns 20 and assigns to arrayLength
If such a function existed, it surely would not return a signed integer. It
would return a size_t instead. Also, since passing arrays to functions in
tricky and since there is nothing to compute (the size is known) a function
doesn't make much sense. Note that using template functions it can actually
be done and make sense, but don't bother with this for now. Until then:
size_t size = (sizeof characterArray)/(sizeof *characterArray);
What about:
void f(int array[32])
{
size_t size = (sizeof array)/(sizeof *array);
// ...
}
Using division (wrapped up in a macro) has the distinct drawback
that it can accidentally be misused without the compiler
complaining.
Using a template function has the advantage of triggering a
compiler error when it is misused (as in the above). It has the
disadvantage (at least in C++03) of not being a constant
expression, which limits its use.
In C++0x, of course, the solution is to use std::array, which
has the necessary functions. Regretfully, the size is an
absolute part of the type of std::array, so you can't write
something along the lines of:
void f(std::array<int, ?> const& a)
without making f a template, which you generally want to avoid.
I once implemented something along the lines of:
template <typename T>
class ArrayOf { /* ... */ };
template <typename T, int N>
class ConcreteArrayOf : public ArrayOf<T> { /* ... */ };
where ConcreteArrayOf was very similar to std::array, but you
could pass it around as an ArrayOf, without the size being an
integral part of the type. Maybe I should have searched it out
and dusted it off when std::array was being discussed (although
it cannot make all of the guarantees of std::array---in
particular, sizeof(ConcreteArrayOf<T, n>) > n * sizeof(T), where
as sizeof(std::array<T, n>) == n * sizeof(T). (I think the
latter is guaranteed.) Also, my ConcreteArrayOf didn't support
aggregate initialization (but I think that could have been
fixed).
IF the function is defined for array class, what is it call?
An array is not a class type! Lastly, just in case, don't use
char arrays for texts, use std::string instead.
And if you have access to C++0x, don't use C style arrays at
all:-).
--
James Kanze
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]