I'm trying to generate and solve an NxN odd-numbered magic square through dynamic memory allocation but whenever I run the code, it displays nothing on the terminal and the programme ends. I reckon it has something to do with the dynamic allocation of the 2D array, as when I make a normal NxN array with a constant size, the programme runs fine. I'd appreciate any help regarding this!
#include<bits/stdc .h>
#include<cmath>
using namespace std;
void calcuateMagicSquare(int N)
{
int **Array;
Array=new int*[N];
for(int i=0; i<N; i )
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
int nSquare=N*N;
int i=N/2;
int j=N-1;
for(int k=1; k<=nSquare;)
{
if(i==-1 && j==N)
{
j=N-2;
i=0;
}
else
{
if(j==N)
{
j=0;
}
if(i<0)
{
i=N-1;
}
}
if(Array[i][j])
{
j=j-2;
i ;
continue;
}
else
{
Array[i][j]=k ;
}
j ;
i--;
}
int SolutionMagicSquare=N*(N*N 1)/2;
cout << "Solution of the magic Square: " << SolutionMagicSquare << endl;
cout << "MAGIC SQUARE: \n" << endl;
for(int i=0; i<N; i )
{
for(int j=0; j<N; j )
{
cout << setw(4) << Array[i][j] << " ";
cout << endl;
}
}
}
int main()
{
int N;
cout << "Please enter the dimension of the magic square:" << endl;
cin >> N;
calcuateMagicSquare(N);
}
CodePudding user response:
This isn't too bad.
int ** Array=new int*[N];
for(int i=0; i<N; i )
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
The memset is causing your trouble, and it's wrong for two reasons. First, let's say you really wanted to do that. You don't, but let's say you did. How big is sizeof(Array)
. Array is an int **
. On a 64-bit machine, that's 8 bytes. So conveniently, you only destroyed the first pointer.
What you really need to do is this:
int ** Array=new int*[N];
// Don't do this memset, but showing you what it should look like)
memset(Array, 0, sizeof(int *) * N);
for(int i=0; i<N; i )
{
Array[i]=new int[N];
// But this one is safe
memset(Array[i], 0, sizeof(int) * N);
}
Your version was erasing the first pointer -- Array[0]
. I put that first memset in there so you could see what it would look like if you needed it. It's the second one you need. You're clearing out the size of an int times the number of ints that you have.