- What's the difference between those using array[0] and *array?
- Why should either be preferred?
- Do they differ in C++?
(1) No difference in C. No difference for an actual raw array in C++.
(2) No technical grounds to prefer one or the other, but newbies might be confused by the pointer dereference.
(3) In C++ you would normally not use the macro, because it's very unsafe. If you pass in a pointer instead of an actual raw array, code will compile but yield incorrect result. So in C++ you would/should instead use a function template, like …
#include <stddef.h>
typedef ptrdiff_t Size;
template< class Type, Size n >
Size countOf( Type (&)[n] ) { return n; }
This only accepts actual raw array as argument.
It's part of a triad of functions startOf
, endOf
and countOf
that it's very convenient to define so that they can be applied to both raw arrays and standard library containers. As far as I know this triad was first identified by Dietmar Kuehl. In C++0x startOf
and endOf
will most probably be available as std::begin
and std::end
.
Cheers & hth.,