所以對於一個任務,我必須創建一個程序,當用戶輸入一個奇數時創建幻方塊,我已經完成了大部分程序,但由於某種原因,當我嘗試填充正方形我得到未處理的異常在0x00326315魔幻square.exe中:0xC0000005:訪問衝突讀取位置0x00000000用指針創建2d動態數組
我正在使用類並具有廣場的聲明爲int ** square;
下面是代碼
#include<iostream>
#include<iomanip>
#include"MagicSquare.h"
using namespace std;
MagicSquare::MagicSquare(): size(0), maxNum(0), row(0), col(0), curNum(0) //Constructor initialize variables
{
}
MagicSquare::~MagicSquare() //Destructor
{
for (int i = 0; i < size; i++)
{
delete[] square[i];
}
delete[] square; //Delete the dynamically allocated memory
}
void MagicSquare::getSize() //Get the size of the magic square
{
cout << "Please enter an odd number for the number of rows/columns: ";
cin >> size;
while (size % 2 == 0) //Check to see if the number entered is odd
{
cout << "The number you entered is not odd, please enter an odd number: ";
cin >> size;
}
int **square = new (nothrow) int*[size];
for (int i = 0; i < size; i++)
{
square[i] = new (nothrow) int[size];
}
maxNum = size * size;
iCount = new (nothrow) int[size];
jCount = new (nothrow) int[size];
}
void MagicSquare::populateSquare()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
square[i][j] = 0; //This is where the error occurs
}
}
curNum = 1;
col = (size - 1)/2;
square[row][col] = curNum;
curNum += 1;
for (int i = 1; i <= maxNum; i++)
{
row = row - 1;
col = col + 1;
if (col >= size)
col = 0;
if (row < 0)
row = size - 1;
square[row][col] = curNum;
curNum += 1;
}
}
頭文件
class MagicSquare
{
private:
int **square;
int size;
int maxNum;
int row;
int col;
int curNum;
int *iCount;
int *jCount;
public:
MagicSquare();
~MagicSquare();
void getSize();
void populateSquare();
void printSquare();
};
源文件
#include"MagicSquare.h"
#include<iostream>
using namespace std;
int main()
{
MagicSquare mySquare;
int choice = 1;
while (choice == 1)
{
mySquare.getSize();
mySquare.populateSquare();
mySquare.printSquare();
cout << "\n\nWould you like to create another magic square? 1 for yes, 0 for no: ";
cin >> choice;
while (choice != 1 || choice != 0)
{
cout << "\nInvalid input: \nWould you like to create another magic square? 1 for yes, 0 for no: ";
cin >> choice;
}
}
system("pause");
return 0;
}
你爲什麼用'新(nothrow)'沒有檢查返回值?另外,給我們一些編譯。 – tillaert 2014-09-23 20:22:21
老師需要它,我通常不會使用(nothrow) – JBoyden 2014-09-23 20:23:12
您的老師是否真的說過不應該檢查'new'調用的結果,還是僅僅使用'nothrow'?如果是這樣,你應該認真考慮尋找另一個教育點,因爲它有點瘋狂。 (我正準備寫一些類似於tillaert在彈出時寫的東西) – 2014-09-23 20:25:04