Dynamic Memory Allocation

I want to create a multi-dimensional array in runtime in as simple way as possible. so, i tried the following way...

1
2
3
int *rows;
//then i can always create an one dimensional array in the following way
rows= new (nothrow) int[a]; if (rows==0) {cout<<"Memory couldn't be allocated for matrix rows";} //( where a is a dynamic value.) 


so, i tried to extend the same idea to multidimensional array ain the following way
1
2
3
4
5
6
7
 
int **mat;
mat = new (nothrow) int * [b]; if (mat==0){cout<<" error message";}
/*it worked fine, i mean no syntax errors, but now i want to know what kind of structure does it creates...
one dimensional vector with a pointer (likely ) or a two dimensional array(very unlikely)
i want to use it as a two dimensional array... how can that be possible... pls help me...
*/ 


Pls help me... and pls do let me know if my idea is valid or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Matrix
{
      private:
              int *rows; // one dimensional array
              int *cols; // one dimensional array
              int **mat; // two dimensional array
              int i, j; //input value for the rows and matrix of the matrix...
      public:         
             Matrix()
             {}
             void setMatrix()
             {
                cout<<"Please input the Number of rows for the matrix:"; cin>>i;
                cout<<"Please input the Number of columns for the matrix:"; cin>>j; 
                rows= new (nothrow) int[i]; if (rows==0) {cout<<"Memory couldn't be allocated for matrix rows";}
                cols= new (nothrow) int[j]; if (cols==0) {cout<<"Memory couldn't be allocated for matrix columns";}
                mat = new (nothrow) int *[j]; if (mat==0){cout<<"memory allocation error";}
                getNewElements();
             }

             void getNewElements()
             {
             for ( int a = 0; a <i; a++)
                  { cout<<"\n"<<"pls enter the elements for row "<<a<<"\n";
                     for (int b =0; b<j; b++)
                     {cout<<"matrix["<<a<<"]["<<b<<"]";
                       // cin<< mat[a][b];
                     }
                  }
              }
             
};

int main(void )
{
    Matrix a;
    getch();
    a.setMatrix();
    getch();
    return 0;
}
Last edited on
First of all, get rid of the "nothrow"! If you want to handle these errors, catch the exception. Otherwise, just let it crash. Running out of memory is so unlikely that it's probably better to crash right away than to write an error message and continue. It will crash anyway.

To allocate a two-dimentional array, you need to allocate one array of pointers for the "rows", then allocate the columns one at a time in a loop:
1
2
3
4
5
6
7
8
9
10
// Setup
int **mat = new int * [ROWS];
for (int i = 0; i < ROWS; i++)
  mat[i] = new int [COLS];

// Cleanup
for (int i = 0; i < ROWS; i++)
  delete[] mat[i];
delete[] mat;
mat = 0;

See also:
http://cplusplus.com/forum/general/833/
The expression
 
new int*[n];

dynamically allocates and array of n int*s in memory. You would then need to initialise each newly created int* with its own new.

Something like this...
1
2
3
4
5
   int** myInts = new int*[n];
   for(int i = 0; i < n; ++i)
   {
      myInts[i] = new int[n];
   }


However this has its own set of problems. A better solution would be something based on this sort of idea...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   typedef vector<vector<int> > MyMatrixDataType;

   MyMatrixDataType::size_type rows = 10;
   MyMatrixDataType::size_type cols = 10;
   int initialValue = 3;

   MyMatrixDataType a(
      rows,
      vector<int>(
         cols,
         initialValue
      )
   );
   
   cout << "Rows: " << a.size() << '\n';
   cout << "Cols: " << a[0].size() << '\n';
   cout << "a[5][5] = " << a[5][5] << '\n';


Let the standard library worry about memory management and your class can worry about matrix operations.
thank you ropez, it worked... now i have an exception catching mechanism in my code...
Dr Dogg,
i would like to ask some questions regarding the second method
1
2
3
4
typedef vector<vector<int> > Matrix;

   Matrix::size_type rows = 10;
   Matrix::size_type cols = 10;


1
2
3
4
5
6
7
int user_defined_rows, user_defined_columns;

   cin>>user_defined_rows;
   cin>>user_defined_columns;

Matrix::size_type rows = user_defined_rows;
Matrix::size_type rows = user_defined_columns;



can we specify the rows and cols as dynamic values rather than some constants.???

Last edited on
>> can we specify the rows and cols as dynamic values rather than some constants.???
Yes.

vector<T>::size_type is just a typedef for whatever type vector uses to represent lengths and indexes. size_type is often equivalent to size_t or unsigned int but using the typedef from vector ensures that you use the right one.

The vector solution has the additional advantage of being exception safe.
1
2
3
4
5
   int** myInts = new int*[n];
   for(int i = 0; i < n; ++i)
   {
      myInts[i] = new int[n];
   }

This is not safe because if new on line 4 throws, any previous successful allocations by line 4 will not be freed and neither will memory allocated on line 1.

With the vector solution, if anything throws, vector does the right cleanup.

PS. Using vector, the default assignment operator works as well whereas with the manual memory management you would have to overload operator= to do the right thing.
Last edited on
Topic archived. No new replies allowed.