0

我写了以下代码

#include <stdio.h>
#include <stdlib.h>
#define MAX 300003;

int **a, **cost, **prev_x, **prev_y, **b;
int N, M;

int mincost(int n, int m)
{
    //printf("For %d %d\n", n, m);

    printf("prev_x[6][8] = %d\n", prev_x[6][8]);
    printf("prev_y[6][8] = %d\n", prev_y[6][8]);

    printf("cost[%d][%d] %d\n", n, m, cost[n][m]);
    return cost[n][m];
}


int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d %d", &N, &M);

        a  = (int **)calloc(N, sizeof(int));
        b  = (int **)calloc(N, sizeof(int));

        cost = (int  **)calloc(N, sizeof(int));
        prev_x = (int  **)calloc(N, sizeof(int));
        prev_y = (int  **)calloc(N, sizeof(int));

        for(int i = 0; i < N; i++)
        {
            a[i] = (int *)calloc(M, sizeof(int));
            b[i] = (int *)calloc(M, sizeof(int));

            cost[i] = (int *)calloc(M, sizeof(int));
            prev_x[i] = (int *)calloc(M, sizeof(int));
            prev_y[i] = (int *)calloc(M, sizeof(int));
        }

        printf("%d %d\n", N, M);
        printf("prev_y[6][8] = %d\n", prev_y[6][8]);
        printf("prev_x[6][8] = %d\n", prev_x[6][8]);


        char *str = (char *)calloc(M+1, sizeof(char));
        for(int i = 0; i < N; i++)
        {
            scanf("%s", str);
            for(int j = 0; str[j]; j++)
            {
                if(str[j] == '1')
                    a[i][j] = 1;
                cost[i][j] = -1;
            }
        }
        cost[0][0] = 0;

        mincost(N-1, M-1);

    }
}

对于输入

1
7 9
010101110
110110111
010011111
100100000
000010100
011011000
000100101

它在第 13 行给出了分段错误。有人可以解释为什么我无法prev_x[6][8]在 mincost() 中访问

4

1 回答 1

2

要使用calloc,您将元素的数量作为第一个参数传递,元素的大小作为第二个参数传递。

所以要创建数组,它应该是

a  = (int **)calloc(N, sizeof(int*));

要创建元素,您的代码是正确的:

a[i]  = (int *)calloc(M, sizeof(int));

顺便说一句,您的代码可以在典型的 32 位机器上运行,int并且具有相同的大小,但在8 和4int*的 64 位机器上会失败。sizeof(int*)sizeof(int)

于 2013-06-15T08:02:55.900 回答