I'm just speculating, but I don't see why accessing an element of an array like that would be any different for contiguous or non contiguous memory. It seems to me, in both cases you would be looking up a row at an address stored in a pointer and then moving to a specific offset in that row. It's not as if you were doing something like M+10, or M + 30 to get to the element, which would fail if the memory wasn't contiguous.
I may be wrong, but I think even doing something as simple as M[i][j+1] = M[i+1][j-1] will have significant overhead if the memory isn't contiguous.
If I understand it correctly, it does this:
Your code is somewhat confusing but I like your method a lot..
creates an array:
creates an array of pointers whose size matches the number of rows in the original data:
takes each pointer in the pointer array and points it at the data:
I don't undertand what Perspective was talking about here:
which leaves you with this:
Note the pointer rawData is irrelevant and it's not used anymore.
Perspective seems to be saying you can't access the elements using the 2d array notation M[row][col], but instead you have to use 1 dimensional array notation M[n]. However, the 2d array notation works in this example:
Originally Posted by Perspective
using namespace std;
int rows = 2;
int cols = 3;
//Allocate the actual data
int* rawData = new int[rows*cols];
//Allocate pointers to the data
int** data = new int*[rows];
//Point the pointers into the data
for (int i=0; i < rows; ++i)
data[i] = &rawData[cols*i];
//Fill the array using single array notation:
for(i=0; i < rows*cols; i++)
rawData[i] = (i+1)*10; //10, 20, 30, 40, 50, 60
//display array using single dimension notation:
for(int j=0; j < rows*cols; j++)
//display an element of the array using 2d array notation:
cout<<data<<endl; //last element in the array