20130413

How to use new to allocate memory for 3d array in CPP C++


/*How to use new to allocate memory for 3d array. How to use malloc for 3 dimensional array. CPP program for dynamically allocating memory for 3d array. How to write three dimensional array with malloc with new */

#include<iostream>
using namespace std;
int main()
{
// 3 Dimensions Array
// two 3x4 array
int x = 2, y = 3, z = 4;

int i, j, k;
// memory allocation for 3D

int ***array3D = new int**[x];
for(i = 0; i < x; i++)
{
array3D[i] = new int*[y];
for(j = 0; j < y; j++)
{
array3D[i][j] = new int[z];
}
}
// Accessing 3d array elements
for(i = 0; i < x; i++)
{
cout << i << endl;
for(j = 0; j < y; j++)
{
cout << endl;
for(k = 0; k < z; k++)
{
array3D[i][j][k] = (i * y * z) + (j * z) + k;
cout << '\t' << array3D[i][j][k];
}
}
cout << endl << endl;
}
// deleting 3d array
for(i = 0; i < x; i++)
{
for(j = 0; j < y; j++)
{
delete[] array3D[i][j];
}
delete[] array3D[i];
}
delete[] array3D;

return 0;
}

/*OP:
0

0 1 2 3
4 5 6 7
8 9 10 11

1

12 13 14 15
16 17 18 19
20 21 22 23
*/
Previous                             Home                               Next

No comments:

Post a Comment