how do you initialize and uninitialize a multidimensional character array in C++?
Read the FAQ -- you'll find everything you need there!
Creation:
Statically allocated:
char mda[ dim1_size ][ dim2_size ]...[ dimn_size ];
Dynamically allocated: Nested new[]
calls.
Initialization:
Nested for loops; as many for
as your dimensions.
Unitialization: Do you mean Destruction?
Statically allocated: The compiler does this when the stack frame is unwound (or for global variables -- when the program stops running).
Dynamically allocated:
Using nested delete[].
you can initialize a multidimensional array like this:
int grid[2][3] = {1, 3, 5, 2, 4, 6};
in that case the seperate values would be:
grid[0, 0]: 1
grid[0, 1]: 3
grid[0, 2]: 5
grid[1, 0]: 2
grid[1, 1]: 4
grid[1, 2]: 6
A quick snippet - it compiles in g++.
int rows = 10;
int cols = 10;
char** array = new char*[rows];
for( int i = 0; i < cols; ++i ) {
array[i] = new char[cols];
}
//do stuff with array
for( int i = 0; i < cols; ++i ) {
delete array[i];
}
delete array;
This is interesting, and this requires a serious look.
The answer given by roo is a widely used one, but I like his observation - just because it compiles doesn't mean it works
I would think a better solution would be to allocate a contigious block of memory (rows * cols) long and then treat it as a 2D array?
I suggest you use the Boost.Multi_Array library. The dimension of the array has to be provided at compile-time, but the sizes are only used at runtime. That means that you have the advantages of dynamic allocation without the pain of having to deal with memory issues.
Here goes the example from the Boost documentation.
int
main () {
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);
return 0;
}