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!

How to allocate memory for a multi-dimensional array with NEW

Dynamic memory allocation

How to allocate memory for a multi-dimensional array with NEW

by  zBuilder  Posted    (Edited  )
Code:
[Just ignore this line. TGML ARRRRggg! :)]

#include <stdio.h>

int main()
{
int (*Buffer)[3][4]; // Note the brackets around the name- IMPORTANT!
// Also note that the first array element is missing.
int x, y, z;

printf("Starting.....\n");

// Below we allocate memory for the array:
if (!(Buffer = new int[2][3][4])) { printf("Error allocating memory...\n"); return 1; }


// Below we fill the array with data:
for ( x=0; x<2; x++ )
{
for ( y=0; y<3; y++ )
{
for ( z=0; z<4; z++ )
{
Buffer[x][y][z] = x * 100 + y * 10 + z;
}
}

}


//Below we read out the data from the array &amp; print to screen:
for ( x=0; x<2; x++ )
{
for ( y=0; y<3; y++ )
{
for ( z=0; z<4; z++ )
{
printf(" %d ", Buffer[x][y][z] );
}
}

}


// Below we deallocate the memory for the array:
delete [] Buffer;

return 0;
}



Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top