我正在嘗試通過動態記憶體分配生成和解決 NxN 奇數幻方,但是每當我運行代碼時,它在終端上什么都不顯示并且程式結束。我認為這與二維陣列的動態分配有關,因為當我制作一個具有恒定大小的普通 NxN 陣列時,程式運行良好。我將不勝感激有關此的任何幫助!
#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);
}
uj5u.com熱心網友回復:
這還不錯。
int ** Array=new int*[N];
for(int i=0; i<N; i )
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
memset 給你帶來了麻煩,它是錯誤的,有兩個原因。首先,假設你真的很想這樣做。你沒有,但假設你做到了。有多大sizeof(Array)。陣列是一個int **. 在 64 位機器上,這是 8 個位元組。如此方便,您只銷毀了第一個指標。
你真正需要做的是:
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);
}
您的版本正在擦除第一個指標 - Array[0]。我把第一個 memset 放在那里,這樣你就可以看到如果你需要它會是什么樣子。這是你需要的第二個。您正在清除 int 的大小乘以您擁有的 int 的數量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438347.html
上一篇:在C 中使用函式引數定義結構方法
