I am trying to allocate memory for a 2 dimensional array of size declared by the user but am not quite sure how to do this. I read several forums about it to generate the code I have so far but am getting errors about have invalid types int[int] for array subscript. Any help would be appreciated THANKS.
Code:
#include <iostream>
#include <vector>
using namespace std;
void MagicSquare ( int ptr, int n );
void DisplaySquare ( int ptr, int n );
int main(void)
{
int order, **ptr;
cout <<"This program will create a magic square of an odd order\n";
cout <<"Please enter the order number you would like:\n";
cin >> order;
ptr = new int *[order]; //allocates a new array of pointers to int type
for(int i=0; i<order; ++i)
ptr[i]=new int[order]; //allocates space for each pointer making second dimension
if (order%2==1)
MagicSquare( **ptr, order );
else{
delete []ptr;
cout <<"order cannot be even\n";
}
DisplaySquare( **ptr, order );
}
void MagicSquare ( int ptr, int n )
{
int max = n * n;
int i=0;
int j=n/2; // start position
for (int k=1; k<=max; ++k)
{
ptr[i][j]= k;
i--;
j++;
if (k%n == 0)
{
i += 2;
--j;
}
else
{
if (j==n)
j -= n;
else if (i<0)
i += n;
}
}
}
void DisplaySquare( int ptr, int n)
{
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
cout << ptr[i][j] << "\t";
cout << "\n\n\n\n";
}
}