Reorder dimensions of a dynamically allocated array

So I have a 2D pointer array of integers:

1
2
3
4
int** someArray = new int*[firstDimensionSize];

for(int i = 0; i < sizeFirstDimension; i++)
    someArray[i] = new int[secondDimensionSize];


This array can then be accessed in the order:

someArray[first][second];

Is there any way to switch the dimensions of this array without reassigning the contents of the entire array to another 2D array? This is how i'm currently doing things, but it's really freaking slow, and somewhat of a dirty hack.

This is how i'm doing it right now:
1
2
3
4
5
6
7
8
9
10
int** someArraySwitched = new int*[sizeSecondDimension];

for(int i = 0; i < sizeSecondDimension; i++)
    someArraySwitched[i] = new int[firstDimensionSize];

for(int i = 0; i < secondDimensionSize; i++)
{
    for(int j = 0; j < firstDimensionSize; j++)
        someArraySwitched[i][j] = someArray[j][i];
}


With the way dynamically allocated arrays work, I would think there would be some fast trick to switching the dimensions.
I think you have your sizes backwards. ie: you're allocating your second size before your first size =x

Anyway, no, there's no shortcut. Unless you just use a vector:

1
2
3
4
5
std::vector< std::vector<int> > someArray;  // vector of a vector makes it 2D

someArray.resize(firstsize);
for(int i = 0; i < firstsize; ++i)
  someArray[i].resize(secondsize);
With the way dynamically allocated arrays work, I would think there would be some fast trick to switching the dimensions.


With the way they work (especially the way you've allocated it) there's no possibility of any trick. Your first dimension is a 1D array of int pointers. Your second dimension is a bunch of separate 1D arrays of ints, pointed to by the first dimension pointers. Clearly there's no quick way to reorder it.
Would this work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int** someArray = new int*[firstDimensionSize];

for(int i = 0; i < sizeFirstDimension; i++)
    someArray[i] = new int[secondDimensionSize];

//Fill array

int** someArraySwitched = new int*[sizeSecondDimension];

for(int i = 0; i < sizeSecondDimension; i++)
{
    for(int j = 0; j < sizeFirstDimension; j++)
    {
        someArraySwitched[i] = &someArray[j][i];
    }
}

Last edited on
Nope.
Topic archived. No new replies allowed.