Reputation:
How do you initialize and Uninitialize a multidimensional character array in C++?
Upvotes: 1
Views: 1557
Reputation: 305
I learned it with a tic tac toe board
const int ROW = 3;
const int COLUMN = 3;
char board [ROW] [COLUMN] = {{'O', 'X', 'O'},
{'X', 'X', 'X'},
{'X', 'O', 'X'}};
I hope this helped.
Upvotes: 0
Reputation: 16994
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;
}
Upvotes: 2
Reputation: 25056
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?
Upvotes: 1
Reputation: 7196
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;
Upvotes: 0
Reputation: 10369
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
Upvotes: 0
Reputation: 111150
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[].
Upvotes: 3