所以我開始我的魔方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