2 Replies - 3140 Views - Last Post: 31 October 2012 - 06:32 PM Rate Topic: -----

#1 jjhaag   User is offline

  • me editor am smartastic
  • member icon

Reputation: 48
  • View blog
  • Posts: 1,789
  • Joined: 18-September 07

Dynamic allocation of 2D arrays

Posted 12 October 2007 - 10:50 PM

Description: add to source, compile and run. very brief example usage (basically just the calling syntax) included in the commentstwo functions; the first dynamically allocates a 2D array with a user- or program-specified number of rows/columns; the second deallocates the same array. demonstrates the mutlti-dimensional usage of malloc and free.
/*   allocate2D
/*   function to dynamically allocate 2-dimensional array using malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows and
/*   columns.
*/
void allocate2D(int** array, int nrows, int ncols) {
     
     /*  allocate array of pointers  */
     array = ( int** )malloc( nrows*sizeof( int* ) );
     
     /*  allocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          array[i] = ( int* )malloc( ncols*sizeof( int ) );
     }

}

/*   deallocate2D
/*   corresponding function to dynamically deallocate 2-dimensional array using 
/*   malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows.  
/*   as with all dynamic memory allocation, failure to free malloc'ed memory
/*   will result in memory leaks
*/
void deallocate2D(int** array, int nrows) {
     
     /*  deallocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          free(array[i]);
     }
     
     /*  deallocate array of pointers  */
     free(array);
     
}

/*   EXAMPLE USAGE:    
int** array1;

allocate2D(array1,1000,1000); //allocates a 1000x1000 array of ints

deallocate2D(array1,1000);    //deallocates the same array
*/


Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic allocation of 2D arrays

#2 JackOfAllTrades   User is offline

  • Saucy!
  • member icon

Reputation: 6248
  • View blog
  • Posts: 24,014
  • Joined: 23-August 08

Re: Dynamic allocation of 2D arrays

Posted 25 January 2009 - 06:12 AM

There is no need to cast the results of malloc or calloc in a C program. It is only required in the more type-safe C++ paradigm.
Was This Post Helpful? 0
  • +
  • -

#3 faheemjan500   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 31-October 12

Re: Dynamic allocation of 2D arrays

Posted 31 October 2012 - 06:32 PM

it is very helpful but i need the code for how to display this matrix?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1