Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic memory allocation

Status
Not open for further replies.

SammyDee

Programmer
Apr 11, 2007
1
Hi

Does anybody know where I can find well tested code that dynamically allocates memory for arrays of dimension greater than three? Specifically I need a well tested allocation of a 4D array.

Thank you
 
I've never tried more than 2 or 3 dimensions, but 4 should be pretty much the same thing, just some extra steps...

Something like this looks like it should work, right?
Code:
char**** array4D;
char***  array3D;
char**   array2D;
char*    array;
int i, j, k;

array4D = malloc( 10 * sizeof( char*** ) );

for ( i = 0; i < 10; ++i )
{
   array3D = malloc( 10 * sizeof( char** ) );

   for ( j = 0; j < 10; ++j )
   {
      array2D = malloc( 10 * sizeof( char* ) );

      for ( k = 0; k < 10; ++k )
      {
         array      = malloc( 80 * sizeof( char ) );
         array2D[k] = array;
      }

      array3D[j] = array2D;
   }

   array4D[i] = array3D;
}
 
Seems a popular question at the moment.
my previous answer


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top