0

I'm learning cpp and this is tangentially related to an assignment I'm working on. I'm confused about writing functions that acception dynamic multidimensional arrays. For example, if I have two 1D arrays, one dynamic and the other not, I can pass either of them to the following function and have them both work:

// Regular 1D array
int b[] = {1,2,3};

// Dynamic 1D array
int *p_b;
p_b = new int[3];
for(int i=0;i<3;i++)
{
    p_b[i] = i;
}

//Function prototype. Works when I use printGrid(b) and printGrid(p_b)
void printGrid(int *a);

However, if I have the following situation with a 2D array, then it will only compile when I pass in a dynamic array:

// Regular 2D array
int c[3][3] ={{1,2,3},{4,5,6,},{7,8,9}};

// Dynaimc 2D array
int **p_c;
p_c = new int*[3];
for(int i=0; i<3;i++)
{
    p_c[i] = new int[3];
}
for(int i=0; i<3; i++)
{
    for(int j=0;j<3;j++)
    {
        p_c[i][j] = i+j;
    }
}

// Function prototype - Compiles and works using printGrid2(p_c) but fails to compile     using printGrid2(c)
void printGrid2(int **a);

The code underneath the printGrid function is exactly the same, so it seems wasteful to have two functions, one using a[][] as a parameter and the other using int **a. Am I not undrestand or missing something? Thanks in advance!

pnus
  • 187
  • 12
  • `int[][]` and `int**` are two different types. – dari Aug 08 '14 at 18:14
  • Indeed we have two distinct types here that are laid out differently in memory. [See this similar question](http://stackoverflow.com/questions/8767166/passing-2d-array-to-function) with a lot of good replies. – glampert Aug 08 '14 at 18:20
  • @glampert - Thanks for the link! – pnus Aug 08 '14 at 18:37

1 Answers1

0

This is not uncommon, what you can do is forward printGrid2 to printGrid to leverage the functionality (saves you from having duplicate code and maintenance overhead).

the printGrid2 loops over the first dimension and calls printGrid with something like a[0]..a[n]

Giel
  • 377
  • 1
  • 9