-2

我试图在运行时分配二维数组。数组的大小为 N*N,其中 N 由用户输入。最后,我正在删除分配的内存。但是我遇到了分段错误。我知道当我尝试访问不是由我分配的内存时会发生分段错误。请帮助代码如下:

#include<iostream>
using namespace std;
#include <stdio.h>

int main ()
{
    int t,n;
    int **judge;
    int **result;
    int i,j,l;
    int high;
    float count;
    int item;
    cin>>t;
    while(t-->0)
    {
        cin>>n;
        judge=new int*[n];result=new int*[n];
        for(i=0;i<n;i++)
        {
            judge[i]=new int[n];
            result[i]=new int[n];
        }

        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                cin>>judge[i][j];
            }
        }
        count=0;
        result[0][0]=0;
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                item=0;
                if(j>0&&i>0)
                {
                if(item<result[i][j-1])
                    item=result[i][j-1];
                else if(item<result[i-1][j])
                    item=result[i-1][j];
                }
                else if(i==0)
                {
                    if(item<result[i][j-1])
                        item=result[i][j-1];
                }
                else if(j==0)
                {
                    if(item<result[i-1][j])
                        item=result[i-1][j];
                }

                result[i][j]=judge[i][j]+item;
            }
        }

        if(result[n-1][n-1]<0.0)
            cout<<"Bad Judges"<<endl;
        else
        {
            count=(result[n-1][n-1]/(float)n);
            cout<<count<<endl;
        }

        for( i = 0 ; i < n  ; ++i)
        {
            delete[] result[i] ;
        }
        delete[] result;
        for(i = 0 ; i < n ; ++i)
        {
            delete[] judge[i] ;
        }
        delete[] judge;
        /* for(i=0;i<n;i++)
        {
            delete[] judge[i];
            delete[] result[i];       
        }*/
        // delete[] judge;
        //delete[] result;
    } 
}
4

2 回答 2

3

你循环judge直到n+2你没有分配那么多。

在这三行中:

for(int i = 0 ; i < n + 2 ; ++i)
{
   delete[] judge[i] ;
}

顺便说一句,这不是您访问尚未分配的内存的唯一时间:

for(i=1;i<n+1;i++)
{
   for(j=1;j<n+1;j++)
   {
     cin>>judge[i][j];
   }
}

在这里i并且j可能达到n,而您的分配允许值高达n -1.

于 2012-12-13T14:59:16.290 回答
0

有许多循环,例如

for(i=1;i<n+1;i++)

在 C++ 中,数组从 0 开始索引,因此您应该使用 [0..n) 代替

for(i=0;i<n;i++)
于 2012-12-13T15:03:38.903 回答