为什么运行此代码会出现运行时错误?

时间:2014-11-28 07:00:51

标签: c algorithm sigsegv

我正在尝试解决有关codechef的问题:http://www.codechef.com/problems/SUMTRIAN 问题陈述:

Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
on each path the next number is located on the row below, more precisely either directly below or below and one place to the right;
the number of rows is strictly positive, but less than 100
all numbers are positive integers between O and 99.
Input:
2
3
1
2 1
1 2 3
4 
1 
1 2 
4 1 2
2 3 1 1 

Output:
5
9

这是我提交的代码:

#include<stdio.h>

int maximum(int** s,int row,int col)
{
    int i,j,m[row][col];
    //m[0][0]=s[0][0];
    for (i = 0; i <row; ++i)
    {
        for (j = 0; j < row; ++j)
        {
            m[i][j]=0;
        }
    }
    for(i=0;i<row;i++)
    {
        for(j=0;j<=i;j++)
        {   

            if(i==0&&j==0)
                m[i][j]=s[i][j];
            else if(j==0)
                m[i][j]=m[i-1][j]+s[i][j];
            else if(i==0)
                m[i][j]=s[i][j];
            else if(m[i-1][j]>m[i-1][j-1])
                m[i][j]=m[i-1][j]+s[i][j];
            else
                m[i][j]=m[i-1][j-1]+s[i][j];
            //printf("m%d %d %d\n",m[i][j],i,j );

        }
    }
    for (i = 0; i <row; ++i)
    {
        for (j = 0; j < row; ++j)
        {
            //printf("%d\n",m[i][j] );
        }
    }
    int max=0;
    for (i = 0; i <row; ++i)
    {   //printf("%d\n",m[row-1][i] );
        if(m[row-1][i]>max)
            max=m[row-1][i];
    }
    return max;
}


    int main()
    {
        int t;
        scanf("%d",&t);
        while(t--)
        {   
            int n,i,j,*p[10],**pf;

            scanf("%d",&n);
            int s[n][n];
            for(i=0;i<n;i++)
            {
                for(j=0;j<=i;j++)
                {
                    s[i][j]=0;

                }
            }   
            for(i=0;i<n;i++)
            {
                for(j=0;j<=i;j++)
                {
                    scanf("%d",&s[i][j]);

                }
                p[i]=s[i];


            }
            pf=p;

            int sum=maximum((int**)pf,n,n);
            printf("%d\n",sum);


        }



        return 0;
    }   

这段代码给出了SIGSEGV。我不知道为什么?我没有太多的内存。堆栈没有得到太多的使用。我正在初始化每个元素。唯一的问题可能是数组索引输出但是我不认为这会发生在任何地方。请帮助!

1 个答案:

答案 0 :(得分:0)

    for (j = 0; j < row; ++j)
    {
        m[i][j]=0;
    }

我认为这里的row应该是col