Converting two dimensional array to double pointer (T[][]-->T**)

May 14, 2011 at 2:13am
How can I convert a two dimensional array to a double pointer?
1
2
int f[2][3]={{1,2,3},{4,5,6}};
int** dreamon=f;

The above does not work, giving the error
Cannot convert ‘int (*)[3]’ to ‘int**’ in initialization

I understand that dimensions are lost in this conversion, and it does not affect my code.

Thanks for your help!
May 14, 2011 at 2:30am
You can't. They're completely different.

Read this: http://cplusplus.com/forum/articles/17108/
May 14, 2011 at 5:39am
Your article is very informative. Thank you for your quick reply.

I gather that double pointers are a one dimensional array of pointers whose memory is not stored consecutively. However, two dimensional array memory is consecutively stored. Then this should not be a problem, I would just have to find the pointer of each 1D array referenced by the 2D array and assign it to the nth position. That is, code resembling the following:

1
2
3
4
5
6
7
int f[2][3]={{1,2,3},{4,5,6}};
int **t;
for(int i=0;i<2;i++)
{
    t[i]=new int*[3];
    *t[i]=*f[i];
}


But I want to put this in a function twodimraTodblptr(f[][]), which needs dimensions, and I am doing all of this to avoid dimensions. So perhaps I can reduce the two dimensional array into a one-dimensional one, as your article highlights:

1
2
3
4
5
int f[2][3]={{1,2,3},{4,5,6}};
int g[2*3];
for(int i=0;i<2;i++)
    for(int j=0;j<3;j++)
        g[2*i+j]=f[i][j];

and pass this to a function, which does not require its dimensions, along with its width:

 
int **u=funkshin(g,3);


1
2
3
4
5
6
7
8
9
10
11
int** funkshin(int[] m,int width)
{
    int **t=new int*[m.length/width];
    for(int i=0;i<m.length/width;i++)
    {
        t[i]=new int[width];
        for(int j=0;j<width;j++)
            t[i][j]=m[m.length/width*i+j];
    }
    return t;
}
May 14, 2011 at 5:48am
I would just have to find the pointer of each 1D array referenced by the 2D array and assign it to the nth position. That is, code resembling the following:


That's one way to do it. Code would look more like this:

1
2
3
4
5
6
int f[2][3]={{1,2,3},{4,5,6}};
int **t = new int*[2];
for(int i=0;i<2;i++)
{
    t[i] = &f[i][0];
}


But of course then you have to remember to delete[] t.

Your funkshin function is more like it's allocating an entirely separate 2D array and copying all the data over, which is a little much.


The main point of the article was to encourage the practice of objectifying these kinds of things. It's better to just make some kind of array2d class and use that instead. Then you don't have to worry about whether or not you have a straight 2d array or a nested new array. Nor do you have to worry about who's responsible for cleanup, etc.

In fact I made such a class for someone recently...

http://www.cplusplus.com/forum/general/42747/#msg231082
Topic archived. No new replies allowed.