Flattening a 2D array efficiently

Hi,
I need to flatten a 2D array **A efficiently, so I was thinking at two methods:

1.

int k=0;
for(int i=0;i<lines_A;i++)
for(int j=0;j<lines_A;j++){
p[k]=A[i][j];
k++;
}

or (and I think this is more effective):
2.

double *p;
p=&A[0][0];

Now I have a problem in the second case, I wonder at the end of my program should I deallocate both *p and **A ? Or, since both points at the same memory location only A must be deallocated ?

=========================================

A different question will be if I can use the same trick to create a 2D array from a 1D array. Say I already have a *A vector full of data and I need to access this as a 2D array, something like:

double **B;
*B=A;

Thanks,

Do
Multidimensional arrays tend to be REALLY annoying when you're using arrays of arrays. Generally, people use the formula y*width+x to simulate a 2d array in a 1d array. A class similar to the following could be used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
struct array{
    T* data;
    int w,h;
    array():data(NULL),w(0),h(0){}
    array(int width,int height){
        data=new T[width*height];
        w=width;
        h=height;}
    ~array(){
        delete[] data;}
    T& operator()(int x,int y){
        return data[y*w+x];}};

I guess when it's stored like this, it's already flattened, if that's what you mean.
Topic archived. No new replies allowed.