I need to write a program that generates a magic square of an odd number between 3 and 15. I have written out this much code, and when i type in 3 for the number it gives me the correct square. but any other odd number it gives me an error. Help me Im lost lol.

``````#include <iostream>
#include <iomanip>

using namespace std;

{
int x;
cout<<"Enter a positive odd integer square size of 3 or more: ";
while(1)
{
cin>>x;
if(x>=3 && x%2==1)
{
return x;
}
else
{
cout<<"Enter a positive odd integer square size of 3 or more: ";
}
}
cout<<endl;
}

int main()
{

int k,g;
int unit;
int row,col,newRow,newCol;
int square[n][n];

for(k=0 ; k<n ; k++) {
for(g=0 ; g<n ; g++) {
square[k][g] = 0;
}
}

unit= 1;
row= 1;
col= (n+1)/2;
k= 1;
square[row-1][col-1]=k;

for(k=2 ; k<=n*n ; k++)
{
newRow= row - 1;
newCol= col + 1;
if (newRow==0 && newCol==(n+1))
{
newRow = row + 1;
newCol = n;
row = newRow;
col = newCol;
square[row-1][col-1]=k;
}
else
{
if(newRow==0)
{
newRow= n;
}
if(newCol==(n+1))
{
newCol= 1;
}
if(square [newRow-1][newCol-1]==0)
{
row=newRow;
col=newCol;
square[row-1][col-1]=k;
}
else
{
newRow= row + 1;
newCol= col;
if(newRow==(n+1))
{
newRow= 1;
}
row= newRow;
col= newCol;
square[row-1][col-1]=k;
}
}
}

// print and free the square
for(int i=0; i<n ;i++)
{
for(int j=0; j<n ; j++)
{
cout<<setiosflags(ios::left) << setw (5) << square[i][j];
}
cout<<endl;
delete[] square[i];
}
free(square);
system("pause");
return 0;
}``````
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by stvnddich

There are two glaring errors, namely

``````delete[] square[i];
// and
free(square);``````

Simply delete those lines because `square` is not dynamically allocated -- doing that may fix the program.

Perhaps see Freestore management.

This did fix the program, thanks so much for your help!!