Thread: allocate mem for a multi-dimensional array?

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    3

    allocate mem for a multi-dimensional array?

    How do I allocate memory for a two-dimensional array?

    Code:
    double* array;
    
    array = new double[10][3];
    does not work...

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    int main(void)
    {
    	double** array; //pointer to a pointer
    	int x,y;
    
    	array = new double*[10];//Set first dimentions
    
    	for(x = 0;x < 10;x++)
    		array[x] = new double[3];//Set second dimentions
    
    	for(x = 0;x < 10;x++)
    		for(y = 0;y < 3;y++)
    			array[x][y] = 2.69; //Do stuff with array
    			
    	for(x = 0;x < 10;x++)
    		for(y = 0;y < 3;y++)
    			cout << array[x][y] << endl;//Show results
    		
    	for(x = 0;x < 10;x++)
    		delete [] array[x];//Clean up!!
    
    	delete [] array;//Clean up!!!
    	
      return 0;
    }
    Bit long winded, but it should work......the plus to this is you can substitute the 10 & the 3 with variables, so the array can be whatever size you wish

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    13
    I thought

    double array[10][3];

    auto allocates mem for it?

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Originally posted by blood.angel
    I thought

    double array[10][3];

    auto allocates mem for it?
    It does, but as gunne was using the new operator, I assumed he/she wanted the array to be declared on the freestore and not the stack.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why can't you allocate a 2D array like this?
    By rudyman in forum C++ Programming
    Replies: 7
    Last Post: 07-22-2008, 01:47 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Dynamic Mutli dimensional Array question.
    By fatdunky in forum C Programming
    Replies: 6
    Last Post: 02-22-2006, 07:07 PM
  4. Replies: 6
    Last Post: 04-26-2004, 10:02 PM
  5. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM