1
int main (void)
{   
    int i,j;
int n;
int **P;
int *d;

scanf("%d",&n);

d=(int*)malloc(sizeof(int)*(n+1));

P=(int**)malloc(sizeof(int*)*(n+1));

for(i=0;i<=n+1;i++)
    P[i]=(int*)malloc(sizeof(int)*(n+1));

for(i=0;i<n+1;i++)
    scanf("%d",&d[i]);
minimult(n,d,P);
order(1,n,P);

free(d);
for(i=0;i<n+1;i++)
    free(P[i]);
free(P); //<----------------when execute here!!!!
return 0;
}
int minimum (int **M,int *d,int i, int j)
{
int count;
int temp,temp2;
for(count=i;count<=j-1;count++)
{
    temp=M[i][count]+M[count+1][j]+d[i-1]*d[count]*d[j];
    if(M[i][j]>temp||count==i)
    {
    M[i][j]=temp;
    temp2=count;
    }
}
return temp2;


}

int minimult(int n, int * d, int **P)
{
int i,j,k,diagonal;
int **M=(int**)malloc(sizeof(int*)*(n+1));
int result;
for(i=0;i<n+1;i++)
    M[i]=(int*)malloc(sizeof(int)*(n+1));
for(i=1;i<=n;i++)
    M[i][i]=0;
for(diagonal=1;diagonal<=n-1;diagonal++)
    for(i=1;i<=n-diagonal;i++)
    {
        j=i+diagonal;
        P[i][j]=minimum(M,d,i,j);
    }
result=M[1][n];
for(i=0;i<n+1;i++)
    free(M[i]);
free(M); 
return result;
}

This algorithm is solving optimized matrix multiplication order. Input was 4 2 3 4 5. When I delete that line, it operates successfully.

What's the problem?

4

1 回答 1

2

在您的分配循环中P[i],您循环一到多次并覆盖分配内存的末尾P。将循环条件更改为i < n + 1(或i <= n)。

于 2013-04-30T07:54:16.610 回答