Mrme,
We always had fun with this problem when I was working in the lab in college, because it is such a great example of the memory handling skills that so often hamper a great implementation. It is a little bit of a pain, and it does look like we're re-inventing the wheel. But the point of the exercise was to avoid complex class interfaces, and of course hone the memory "bookkeeping" skills. I threw this together using your specifications:
Code:
#include<iostream>
#include<iomanip>
using namespace std;
double **getMatrix( int width, int height );
void releaseMatrix( double **grid, int width, int height );
void printMatrix( double **grid, int width, int height );
int main(int argc, char *argv[])
{
double **grid;
int j;
int room_width = 10;
int room_height = 10;
grid = getMatrix( room_width, room_height );
// perform operations on your grid...
for( j = 0; j < room_width; j++ )
{
grid[ j ][ j ] = j*2.0 + 1.0;
}
printMatrix( grid, room_width, room_height );
releaseMatrix( grid, room_width, room_height );
system("pause");
return 0;
}
double **getMatrix( int width, int height )
{
double **allocate;
int j;
int k;
allocate = new double*[width];
if( NULL == allocate )
{
cerr << "Memory allocation problem...exiting." << endl;
exit( 1 );
}
for( k = 0; k < width; k++ )
{
allocate[k] = new double[height];
if( NULL == allocate[k] )
{
cerr << "Memory allocation problem...exiting." << endl;
exit( 1 );
}
for( j = 0; j < height; j++ )
{
allocate[k][j] = 0.0;
}
}
return allocate;
}
void releaseMatrix( double **grid, int width, int height )
{
int k;
if( NULL != grid )
{
for( k = 0; k < width; k++ )
{
delete [] grid[k];
}
delete [] grid;
}
return;
}
void printMatrix( double **grid, int width, int height )
{
int j;
int k;
for( j = 0; j < height; j++ )
{
for( k = 0; k < width; k++ )
{
cout << setw(4) << grid[k][j];
}
cout << endl;
}
return;
}
The two dimensional array, which you called grid, can be allocated and de-allocated as necessary. I must admit that it is a little stilted, but it is very readable and can be applied to aggregate data types too. The output of this code is:
Code:
1 0 0 0 0 0 0 0 0 0
0 3 0 0 0 0 0 0 0 0
0 0 5 0 0 0 0 0 0 0
0 0 0 7 0 0 0 0 0 0
0 0 0 0 9 0 0 0 0 0
0 0 0 0 0 11 0 0 0 0
0 0 0 0 0 0 13 0 0 0
0 0 0 0 0 0 0 15 0 0
0 0 0 0 0 0 0 0 17 0
0 0 0 0 0 0 0 0 0 19
Press any key to continue . . .
I think that the syntax I used accounts for the update to the standard (C99), where the delete operator required the braces...I think that arrays got an extra atom associated with them for the heap management, but I am only speculating. The text I am using is Victor Shtern's CORE C++: A Software Engineering Approach. It was printed in 2000, and has been accurate in every application I have identified. Is this what you had in mind, Mrme?
Best Regards,
New Ink -- Henry