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.
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.
Micko:
Your code is somewhat confusing but I like your method a lot..
If I understand it correctly, it does this:
1)
creates an array:
1 <-------rawData
1
1
2
2
2
2)
creates an array of pointers whose size matches the number of rows in the original data:
int* <-------data
int*
3)
takes each pointer in the pointer array and points it at the data:
1 <-----int*
1
1
2 <-----int*
2
2
4)
which leaves you with this:
1 <-----int*<-------------data
1
1
2 <-----int*
2
2
Note the pointer rawData is irrelevant and it's not used anymore.
I don't undertand what Perspective was talking about here:
Originally Posted by
Perspective
>>double *M = new double[size*size]; // doesn't work
This does work if you index it properly. instead of indexing M[x][y], you use M[ x*size + y ].
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:
Code:
#include <iostream>
using namespace std;
int main()
{
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++)
{
cout<<rawData[j]<<endl;
}
//display an element of the array using 2d array notation:
cout<<data[1][2]<<endl; //last element in the array
return 0;
}