【发布时间】:2009-11-07 20:14:55
【问题描述】:
所以我开始了我的魔方硬件,我要求用户输入一个奇数,它会创建一个魔方。我必须使用指针和数组,因为这是我迄今为止所学到的。不是问如何做魔方,而是导致分段错误的原因,我可能没有正确地做指向二维数组的指针
#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;
}
【问题讨论】:
标签: pointers segmentation-fault multidimensional-array