因此,对于作业,我必须创建一个程序,当用户输入一个奇数时会创建魔术方块,我已完成大部分程序但由于某些原因当我尝试填充方块时,我得到0x00326315处的未处理异常在magic square.exe中:0xC0000005:访问冲突读取位置0x00000000
我使用类并将square的声明作为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;
}
答案 0 :(得分:2)
您在square
方法中定义了一个名为getSize()
的局部变量:
int **square = new (nothrow) int*[size];
。
所以你为局部变量留出空间,但从不为类的字段留出空间。
将此行更改为
square = new (nothrow) int*[size];
还要认真考虑检查通话结果。
答案 1 :(得分:1)
访问冲突读取位置0x00000000告诉您,您正在尝试访问NULL指针。
原因可能是,new
的至少一次调用失败了。你应该在分配数组时检查:
int **square = new (nothrow) int*[size];
if(square == NULL)
//Handle error here
for (int i = 0; i < size; i++)
{
square[i] = new (nothrow) int[size];
if(square == NULL)
//Handle error here
}
但我猜这不是原因。如果我看到它,你有两个功能:
void MagicSquare::getSize()
void MagicSquare::populateSquare()
但是int **square
是在getSize中创建的,所以如果你调用populate square,这个变量就不再存在了。
如果你的班级是:
class MagicSquare
{
private:
int **square;
public:
//Methods
}
在getSize中,您必须将地址存储在classes成员变量中,而不是您刚刚创建的本地变量:
square = new (nothrow) int*[size]; //without int **