-2

I am generating 3 nxn sized magic squares (Where n is an odd number between 3 and 15), and want to pass the 2d arrays they are stored in to this function:

void printSquare(int n, int square[n][n], int b){
    cout << "Magic Square #" << b << " is:\n";

    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
            printf("%3d ", square[i][j]);
        printf("\n");
    }
}

The arrays are passed to the function like this:

 printSquare(n, magicSquare, 1);

However, no matter how I try to change it to get the function to accept the 2d array with undefined size, I keep getting errors like "candidate function not viable: no known conversion from 'int [n][n]' to 'int (*)[n]' for 2nd argument". How can I fix this so that I can use the 2d array in my function?

  • Change language to C? Is that an option? – anatolyg Feb 17 '16 at 17:16
  • 1
    How are you generating them? If you are using a `int**` why not have your function take that? – NathanOliver Feb 17 '16 at 17:16
  • 1
    Shame on you. https://www.google.com/search?q=How+can+I+pass+a+variably+sized+2d+array+to+a+function pick a duplicate and close the question. – Karoly Horvath Feb 17 '16 at 17:17
  • 2
    Possible duplicate of [Passing a multidimensional variable length array to a function](http://stackoverflow.com/questions/14548753/passing-a-multidimensional-variable-length-array-to-a-function) – Donnie Feb 17 '16 at 17:31

1 Answers1

0

In c++ multi-dimensional arrays need the sizes of all but the top dimension as part of the type. So the type of a 2d array could be int a[][3], but not int a[][].

Assuming that n is not a constant, your best bet is to treat square as a one dimensional array and then use n, which you passed in, to index into square, like so:

for(int i=0; i<n*n; i++)
{
    printf("%3d ", square[i]);
    if((n-1)==(i%n))
        printf("\n");
}
Kyle A
  • 848
  • 7
  • 17
  • More complete answers can be found to this duplicate question: [Passing a 2D array to a C++ function](http://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function?rq=1) – Kyle A Feb 17 '16 at 17:31
  • You can use a pointer to a pointer, you don't have to collapse it to a 1D array. i.e. int** in the example above. – James Elderfield Feb 17 '16 at 17:42