2009-11-07 142 views
0

所以我开始我的魔方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; 
} 

回答

4

int row=odd;应该int row=odd-1;
你跟排后的索引,所以你能数组[size_of_array],它总是出界。

+1

这可能是正确的,但因为这个问题涉及到一门功课,我认为它实际上是更有益告诉Raptrex如何找到比错误告诉他错误在哪里...... – 2009-11-07 20:23:08

+0

谢谢,这样做很有意义 – Raptrex 2009-11-07 20:24:56

1

的第一件事,当你得到一个分割故障做要么抢调试并追踪段错误发生的位置,或者(更简单),在代码中为cerr添加大量打印输出,以便在段错误之前可以看到有多少代码被执行。

附加提示:使用cerr而不是cout,以避免缓冲,否则可能导致您无法看到错误发生前应获得的某些输出,并且始终为每个打印输出添加一个换行符,以避免在下一次提示时出现换行在运行程序的shell中。

0

此:

ptr[row][column] = 1; 

访问阵列出界(提示:PTR [行]将有可能在大多数malloc实现NULL)。

1

gdb能够准确地告诉你seg段发生的时间,并让你从中打印数据。它可能是您找出段错误发生的最佳选择。

与-g编译程序(假设你使用GCC)