简体   繁体   English

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

[英]Unable to understand why segmentation fault is occuring

I have written the following code 我写了以下代码

#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);

    }
}

For the input 输入

1
7 9
010101110
110110111
010011111
100100000
000010100
011011000
000100101

it gives segmentation fault on line 13. Can some explain why I can't access prev_x[6][8] in mincost() 它在第13行给出了分段错误。可以解释为什么我不能在mincost()中访问prev_x[6][8]

To use calloc you pass the number of elements as the first argument and the size of the element as the second. 要使用calloc您可以将元素数作为第一个参数传递,将元素的大小作为第二个参数传递。

So to create the arrays it should be 所以要创建数组应该是

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

And to create the elements your code is right: 并创建代码正确的元素:

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

Incidentally, your code would work in a typical 32-bit machine, as int and int* have the same size, but will fail in a 64-bit machine, where sizeof(int*) is 8 and sizeof(int) is 4. 顺便提一下,你的代码可以在一个典型的32位机器上工作,因为intint*具有相同的大小,但是在64位机器中会失败,其中sizeof(int*)是8而sizeof(int)是4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM