【问题标题】:Segmentation fault, using pointers to pointers分段错误,使用指向指针的指针
【发布时间】: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


    【解决方案1】:

    int row=odd; 应该是int row=odd-1;
    您稍后会使用行进行索引,因此您会到达数组 [size_of_array],它总是超出范围。

    【讨论】:

    • 这可能是正确的,但是由于这个问题涉及到家庭作业,我认为告诉Raptrex如何找到错误实际上比告诉他错误在哪里更有帮助......跨度>
    【解决方案2】:

    当您遇到分段错误时,首先要做的是获取调试器并准确跟踪发生段错误的位置,或者(更简单)在代码中添加大量打印输出到 cerr,这样您就可以看到在段错误之前执行了多少代码。

    附加提示:使用 cerr 而不是 cout,以避免缓冲,否则可能会阻止您在错误之前看到一些应该得到的输出,并且总是在每个打印输出中添加一个换行符以避免它被下一个提示破坏运行程序的 shell。

    【讨论】:

      【解决方案3】:

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

      使用 -g 编译您的程序(假设您使用的是 GCC)

      【讨论】:

        【解决方案4】:

        这个:

        ptr[row][column] = 1;
        

        越界访问数组(提示:在大多数 malloc 实现中,ptr[row] 可能为 NULL)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-02
          • 2017-03-10
          • 2018-01-23
          • 2018-07-29
          • 1970-01-01
          • 1970-01-01
          • 2010-10-21
          相关资源
          最近更新 更多