0

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;
}
1
  • buffer[i*3+j] = dyn_array[i][j]? Commented Apr 2, 2012 at 22:19

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this. Would this apply to 3D arrays also? Also, how would I go about retrieving specific array elements from the buffer? Is it the same as usual ie. arr[1][2]=4; or does it take a different form?
It'll work for any number of dimensions. You can write a wrapper access function, but it has to be round brackets (operator()), since the square brackets can only take one single argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.