所以我开始我的魔方HW,在那里我要求用户输入一个奇数,并且它会创建一个魔术方块。我必须使用指针和数组,因为这是我迄今为止所了解到的。不问如何做幻方,但什么原因造成分段错误,即时通讯可能不是做指针二维数组正确分割错误,使用指针指针
#include <iostream>
using namespace std;
int main()
{
int **ptr;
int odd;
do
{
cout << "Enter a odd number to create a magic square: ";
cin >> odd;
}while(odd % 2 != 1);
ptr = new int *[odd]; //creates a new array of pointers to int objects
for(int i = 0; i < odd; i++)
ptr[i] = new int[odd];
//set it all to 0
for(int i = 0; i < odd; i++)
{
for (int j = 0; j < odd; j++)
{
ptr[i][j] = 0;
cout << ptr[i][j];
}
}
int row = odd;
int column = odd/2;
int lastrow = row;
int lastcolumn = column;
//begin adding numbers to magic square
ptr[row][column] = 1;
for (int i = 2; i < odd * odd; i++)
{
}
//delete
for(int i = 0 ; i < odd; i++)
delete [] ptr[i];
delete [] ptr;
return 0;
}
这可能是正确的,但因为这个问题涉及到一门功课,我认为它实际上是更有益告诉Raptrex如何找到比错误告诉他错误在哪里...... – 2009-11-07 20:23:08
谢谢,这样做很有意义 – Raptrex 2009-11-07 20:24:56