-
Dynamc Memory
I need to declare a bidimensional arrey but using dynamic memory. (C++)
I used:
int x,y;
cin>>x;
cin>>y;
int **m=new[x][y];
ERROR: Parse error before '['
I also used:
int **m= new int[x][y];
ERROR: Assigment to 'int **' from 'int (*)[((y-1)+1)]'
please help me...
-
Well, what you're REALLY doing is making an array of arrays.
So, do this:
Code:
int ** m;
m = new int * [x];
for (int i = 0; i < x; i++){
m[i] = new int[y];
}
//Now, you can use the array.
//To deallocate, deallocate in reverse order you allocated:
for (int i = 0; i < x; i++){
delete[] m[i];
}
delete[] m;
-
Thnks a lot
Thnks a lot you've saved my life...
-
Not as eloquent as the first but a bit more efficient.
Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int x, y;
cout << "Enter number of arrays: " << flush;
cin >> x;
cout << "Enter the number in each array : " << flush;
cin >> y;
int * pArry = new int[ x * y ];
if( !pArry )
throw bad_alloc( );
for ( int i = 0; i < x; i++ )
{
for( int j = 0; j < y; j++ )
{
(pArry + i)[ j ] = j + i;
}
}
for ( i = x - 1; 0 <= i; i-- )
{
for( int j = y - 1; 0 <= j; j-- )
{
cout << " j = " << j << " i = " << i << " j + i = pArry[i][j] = " << (pArry + i )[ j ] << endl;
}
}
delete pArry[];
return 0;
}