Dynamc Memory

This is a discussion on Dynamc Memory within the C++ Programming forums, part of the General Programming Boards category; 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]; ...

  1. #1
    Unregistered
    Guest

    Exclamation 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...

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    412
    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;

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    7

    Thnks a lot

    Thnks a lot you've saved my life...

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    156
    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;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-13-2008, 02:14 AM
  2. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  4. reading files into memory
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 11-30-2005, 03:39 PM
  5. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21