C ++ dynamically allocated array of statically sized arrays
I need to create a structure that contains the variable number 'char [2], i.e. static arrays of 2 characters.
My question is, how do I allocate memory for x of a char [2].
I tried this (assuming int x is defined):
char** m = NULL;
m = new char[x][2];
...
delete [] m;
(it didn't work)
I understand that I can use std :: vector <char [2]> as a container, but I'm curious how this would be done with raw pointers.
I am very new to C ++ and am trying to learn.
source to share
I find the following code to be 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 know about the internal structure of wchar, the code will be more readable if we declare it like this:
// 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 are using C ++, there is 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;
Another fairly safe compile-time range check option:
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;
}
source to share
unsigned x=10;
typedef char A2[2];
A2 *m=new A2[x];
m[0][1]='a';
m[9][0]='b';
delete[] m;
C multidimensional arrays (where all but the first dimensions are constant) are laid out contiguously.
If you want a (potentially jagged) multidimensional array that is a 1d array of 1d arrays, then you need to loop:
char **m=new char *[x];
for (unsigned i=0;i<x;++i) m[i]=new char[2];
...
for (unsigned i=0;i<x;++i) delete[] m[i];
delete[] m;
source to share
You end up sizing the array and then using a new one and treating it as a two dimensional array.
But for a good discussion about this, you can take a look: http://www.velocityreviews.com/forums/t283481-dynamic-multidimensional-arrays.html
source to share