I have a code segment that generates a dynamic 3D array of random numbers and allocates it to a block of memory. I think I have it correct but how do I test whether or not it is all located in a contiguous block of memory? Is there a way? I have a cout function that prints the address of each element to the screen and it seems to be correct but I can’t be sure. I know that I have to free the memory again too but that will come later.
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int ***dyn_array;
int **buffer_1;
int i;
int j;
int k;
int *buffer=new int[5*3*2];//Create a buffer for a block of memory
dyn_array = new int**[5];
buffer_1 = new int *[3];
srand(time(NULL));
cout<<"The address of the buffer is: "<<buffer<<endl;
for(i=0;i<5;i++)
{
dyn_array[i] = &buffer_1[i*3];
for(j=0;j<3;j++)
{
dyn_array[i][j] = &buffer[j*2];
}
}
for(i=0; i<5; i++)
{
for(j=0; j<3; j++)
{
for(k=0; k<2; k++)
{
dyn_array[i][j][k]=rand()%40;
cout<<"dyn array ["<<i<<"]["<<j<<"]["<<k<<"] is: "<<dyn_array[i][j][k]<<endl;
cout<<"Memory Address is: "<<&dyn_array[i][j][k]<<endl;
}
}
}
return 0;
}
Few things first:
You are allocating memory for three integer pointers for
buffer_1(elements 0, 1, 2), but in the loop you access elements 0, 3, 6, 9, 12. (Actually, you take the address of those non-allocated elements, but then you do access them in the loop immediately after) Accessing out-of-bounds elements is undefied behaviorAlso, to answer your main question: the language guarantees that when you allocate an array (statically, or dynamically) the elements occupy a contiguous memory block. Otherwise pointer arithmetics (`int*p=new int[2]; *(p+1)=5;) would not work.
UPDATE from comments:
To achieve the multi-dimensional array effect, the easiest way is to go with your
int *buffer=new int[5*3*2];declaration: it allocates memory for 30 elements. To index into it you could usebuffer[i*3*2+j*2+k]=n, where0<=i<5,0<=j<3,0<=k<2andnis an integer. If you were to allocate the array statically (int buffer[5][3][2];), the internal indexing mechanism would be the same.Also, use named constants (e.g.
const int MAX_DIM1=5;) instead of the raw numbers (aka magic numbers) — will make your code more maintanable