I believe that the following code is more readable than char[n][2]
:
typedef char wchar[2]; // array of two chars
const size_t n = 100; // some const
wchar* x = new wchar[n]; // array of wchars, where wchar is array of two chars
// here is still a problem that you could write the following
x[5][5] = 0; // not what you expected?
delete[] x; // clean up
If we aware of the internal structure of wchar, the code will be more readable if we declare it as follows:
// using struct is just gives names to chars in wchar, without performance drop
struct wchar {
char h;
char l;
};
...
const size_t n = 100; // some const
wchar* x = new wchar[n]; // array of wchars
x[0].h = 0;
x[0].l = 0;
delete[] x; // clean up
And finally, because we use C++, no need to use C arrays:
const size_t n = 100; // some const
typedef std::tr1::array<wchar, n> my_arr;
my_arr* x = new my_arr;
(*x)[0].h = 0;
(*x)[0].l = 0;
delete x;
One more pretty safe option with compile time range checking:
template<int n_max>
struct array_n {
char v[2*n_max];
template<size_t n, size_t s>
char& get() {
BOOST_STATIC_ASSERT( s < 2 );
BOOST_STATIC_ASSERT( n < n_max );
return v[n*2+s];
};
};
int main( int argc, char**argv)
{
const size_t n = 100; // some const
typedef array_n<100> my_arr;
my_arr* x = new my_arr;
x->get<10, 1>() = 0; // ok
x->get<50, 0>() = 0; // ok
x->get<10, 2>() = 0; // compile time error
x->get<500, 0>() = 0; // compile time error
delete x;
}