PDA

View Full Version : pointer arithmetics



darksaga
24th April 2008, 23:26
Hello,

I don't want to start a "flamewar" on how to create a more efficient x-dim-array in c++,
but I'd like to know how to get the 3d equivalent of the following 2d code:


int main()
{
int height, width, depth;
height = width = depth = 3;

//---- 2d case ----
int **pMat2D = NULL;
pMat2D = new int *[height];
pMat2D[0] = new int [height * width];
for (int i = 0; i < height; i++)
pMat2D[i] = &pMat2D[0][(i*width)];

//fill
int number = 0;
for(int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
pMat2D[i][j] = ++number;

//print
for(int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
std::cout << pMat2D[i][j] << " ";
}
std::cout << std::endl;
}

//clean
delete pMat2D[0];
delete[] pMat2D;
//---- 2d case end ----

//---- 3d case ----
int ***pMat3D = NULL;
//???
//---- 3d case end ----
return 0;
}


advantages of the 2d version above:
array access via [][];
data populates one continuous chunk of memory;
fast access on random [i][j]s
no need to calculate offsets during access, as in:


//2d case
int *pMat = new int[x*y];
//access via
pMat[(x * y_size + y)];

//3d case
int *pMat = new int[x*y*z];
//access via
pMat[((z * x_size + x) * y_size + y)];


i need the array to be especially fast with random access on its data.
in the 2d case (in my app) the code from the top performs much better than the code from above, where you access the data via arr[(x * y_size + y)]

i'd like to have a 3d version of the 2d version @ the top, but somehow I can't figure it out.
everything I try, results in some segmentation faults :/...

regards
darksaga

jacek
1st May 2008, 23:31
int * data = new int[ width * height * depth ];
int ** lut1 = new int *[width];
int *** lut2 = new int **[width * height ];

for( int i = 0; i < width; ++i ) {
lut1[i] = & lut2[width*i];
for( int j = 0; j < height; ++j ) {
lut1[i][j] = & data[height*(width*i + j)];
}
}
(not tested of course ;))

Michiel
2nd May 2008, 02:04
The, ehm, preferred way is to create a class that overloads the () operator, which can take any number of parameters. Separate subscripts should be used for jagged arrays, which this is not. It has the added advantage of making the allocation a lot easier.

Just a suggestion.