-2

Why does these code returning a segmentation fault? I searched online but can't find the problem. Could you please help? Is it because of pointer malloc fault?

void multiply(int **a, int n, int m, int **b, int m2, int p, int **c)
{
    int i, j, k;
    for (i = 0; i < n; i++){
        for (j = 0; j < p; j++){
            for (k = 0; k < m; k++){
                c[i][j] += a[i][k] * b[k][j];
                }
            printf("%d", c);}}
}
main()
{
    int **a, **b, **c;
    int n, m, p;
    int i, j;
    scanf("%d", &n); scanf("%d", &m); scanf("%d", &p);
    a = (int **)malloc(n*sizeof(int*));
    for (i = 0; i < n; i++){
        a[i] = (int*)malloc(m*sizeof(int));}
    for (i = 0; i < n; i++){
        for (j = 0; j < m; j++){
            scanf("%d", &a[i][j]);}
    }
    b = (int **)malloc(m*sizeof(int*));
    for (i = 0; i < m; i++){
        b[i] = (int *)malloc(p*sizeof(int));}
    for (i = 0; i < m; i++){
        for (j = 0; j < p; j++){
            scanf("%d", &b[i][j]);}
    }
    c = (int **)malloc(n, sizeof(int));
    for (i = 0; i<n; i++)
        c[i] = (int *)malloc(p, sizeof(int));
    multiply(a, n, m, b, m, p, c);
    free(a);
    free(b);
    free(c);
}

Thanks^^

I edit some code and it is now correct. Thank you guys so much. Cheers!

2 Answers2

1

If you're on an LP64 architecture (int is 32 bits and int* is 64 bits), c is too small, you should use

c = (int **)calloc(n, sizeof(int*));
JeremyP
  • 84,577
  • 15
  • 123
  • 161
1

You have a typo here:

        for (k = 0; k < m; j++){
                           ^

This should be:

        for (k = 0; k < m; k++){
                           ^

Also:

multiply(**a, n, m, **b, m, p, **c);

should be:

multiply(a, n, m, b, m, p, c);

Note that if you had turned on compiler warnings then the compiler would have helpfully pointed out this mistake to you.

Note also that you should not cast the result of malloc in C.

Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560