Reputation: 2689
I'm new to pointers/memory operations and am working on some sample programs. I want to assign a 2D array into a contiguous block of memory in C++. I know I have to create a buffer with the size of the 2D array. I have a small block of code that I wrote which creates the buffer and assigns values to a 2D array, but I don't know how to place the array values into the buffer. Can anyone give me an idea of what to do? I've researched it quite a bit but can't find anything that explains the process in terms I understand. I know that vectors are probably a better option but I want to get to grips with array operations before I move onto that.
Thanks!
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int dyn_array[5][3];
int i;
int j;
srand(time(NULL));
//Need to create a pointer to a block of memory to place the 2D array into
int* buffer=new int[5*3]; //pointer to a new int array of designated size
//Now need to assign each array element and send each element of the array into the buffer
for(i=0;i<5;i++)
{
for(j=0;j<3;j++)
{
dyn_array[i][j]=rand()%40;
cout<<"dyn array ["<<i<<"]["<<j<<"] is: "<<dyn_array[i][j]<<endl;
}
}
return 0;
}
Upvotes: 0
Views: 667
Reputation: 476970
You can address the array in strides, like buffer[i * 3 + j]
. Here j
is the fast index and 3
is the extent of the range covered by j
.
You should generally always store rectangular, multidimensional data in this, flattened-out fashion, because this way you will have one contiguous chunk of memory.
Upvotes: 3