Dynamic Memory Allocation for Two Dimensional Arrays in C++

August 3, 2010 at 3:39 pm 7 comments


In C++, a two-dimensional array can be declared simply like this

int a[10][20];

However, this declaration requires contanst array size and it is inconvenient when the array size vary. To avoid this issue, you can use dynamic two dimensional array. There are several ways to allocate a dynamic two-dimensional array in C++. In this post, I will show you three most frequent methods.

First one is flattening the two dimensional array into one dimensional array and using it as one dimensional array  

//Allocate
int *a = new int[m*n];

//Use a[m][n]
for( int i = 0 ; i < m ; i++)
        for ( int j = 0 ; j < n ; j++)
                 a[i*n + j] = 1;

//Deallocate
delete[] a;
 

Second method is using an array of dynamic one-dimensional arrays. It makes use of dynamic 2D array be easier. However, elements of array may not be continuous in memory

//Allocate
int **a = new int*[m];
for ( int i = 0 ; i < m ; i++)
a[i] = new int[n];
 
 
//Use a[m][n]
for ( int i = 0 ; i < m ; i++)
         for ( int j = 0 ; j < n ; j++)
a[i][j] = 1;
 
//Deallocate
for ( int i = 0 ; i < m ; i++) delete[] a[i];
delete[] a;
 
 
The third one allows all elements of a 2D int array to be contiguous in memory and I like this way most.

 //Allocate
int **a = new int*[m];

int a[0] = new int[m*n];
for ( int i = 1 ; i < m ; i++)  a[i] = a[i-1] + n;
 

 //Use a[m][n]
for ( int i = 0 ; i < m ; i++)
        for ( int j = 0 ; j < n ; j++)
a[i][j] = 1;

  
//Deallocate
delete[] a[0];
delete[] a;
 
If you prefer to performance, I recommend you to use the first method. This may be weird but I have tested on several codes.
Advertisements

Entry filed under: C++ Programming. Tags: , , , , , , .

Linux File System Layout Fixing Dead Pixels and Gray Lines on the iPhone Screen

7 Comments Add your own

  • 1. steve richards  |  April 25, 2012 at 6:12 am

    I tried to compile the third case with g++ and I got the following errors:

    error: array must be initialized with a brace-enclosed initializer
    error: invalid types ‘int[int]’ for array subscript
    error: type ‘int’ argument given to ‘delete’, expected pointer

    Which compiler did you use?

    Reply
    • 2. steve richards  |  April 25, 2012 at 6:30 am

      I just realized that the “int” before a[0] is causing the errors….
      Would it also be possible to access the elements of ‘a’ using a single index? I.e. a[0] … a[i] … a[m*n-1]?

      Reply
  • 3. VELAYUTHAM T  |  July 2, 2012 at 7:33 pm

    I tried your first approach but its failed to retrieve a 4*5 matrix. Then i realized we must change the code to
    for ( int i = 0 ; i < m ; i++)
    for ( int j = 0 ; j < n ; j++)
    a[i*n + j] = 1;

    can you verify this?

    Reply
    • 4. lanvu  |  July 3, 2012 at 9:57 am

      You are right. I just updated ! Thanks .

      Reply
      • 5. VELAYUTHAM T  |  July 3, 2012 at 7:00 pm

        Thanks lot for you..

  • 6. Sainath  |  July 12, 2012 at 12:13 am

    How do we initialize dynamic arrays in C.??
    If we initialize an array as arr[][], it is showing an error.
    Again if we given the array size as arr[m][n] , it is also showing an error.. please help to solve this prob.

    Reply
    • 7. VELAYUTHAM T  |  July 12, 2012 at 5:34 am

      you have to allocate memory using malloc function..

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

/openmp AMD app fixing dead pixel iphone C++ cmd program CPU C sharp dead pixels directory download ibm synthetic data generator Dynamic Dynamic Memory Allocation Edit Environment Variables in Windows Environment Variables error lnk2019: unresolved external symbol _getprocessmemoryinfo@12 referenced in function error lnk2019: unresolved external symbol _ getprocessmemoryinfo@12 referenced in function "void __cdecl printmemoryinfo(unsigned long example code Fixing Dead Pixels and Gray Lines on the iPhone Screen Fixing Dead Pixels on the iPhone Screen Fixing Gray Lines on the iPhone Screen Fix iPhone getprocessmemoryinfo GPU Gray Line iPhone Screen gray lines gray pixels green pixels GUI how to "new" a two-dimension array in C++ how to use ibm quest synthetic data generator ibm data generator ibm quest data generator ibm quest data generator exe ibm quest data mining project ibm quest market-basket synthetic data generator ibm quest market basket market-basket synthetic data generator ibm quest synthetic data generator ibm quest synthetic data generator linux ibm synthetic data generator ibm synthetic generator Intel iPhone Iphone 3G iPhone 3GS iPhone 4 iphone gray lines on startup iphone pixel damage iPhone Screen iPhone screen damage Linux market-basket synthetic data generator Memory Allocation Multicore multithread multi thread multi threaded multithreading mysql extract data into file new OpenCL Path processor quest data generator quest synthetic data generator R SAS Set Environment Variables Set Environment Variables in Windows souce code source code stuck pixels system file two dimension array Windows 7 Windows Vista

%d bloggers like this: