无法理解为什么发生分段错误

时间:2013-06-15 07:52:08

标签: c++ segmentation-fault

我写了以下代码

#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行给出了分段错误。可以解释为什么我无法访问mincost()中的prev_x[6][8]

1 个答案:

答案 0 :(得分:2)

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

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

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

要创建代码正确的元素:

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

顺便提一下,您的代码可以在典型的32位计算机上运行,​​因为intint*具有相同的大小,但在64位计算机中会失败,其中sizeof(int*)是8,sizeof(int)是4。