简体   繁体   中英

Last element of one array overwritten by first element of the next array

I have been working on a problem that involves the multiplication of two matrices and I have to get the elements from the user. However, after getting the elements when I print them the last element of the fist matrix is equal to the first element of the second matrix. As a result I am not getting the correct results. I will be obliged if anyone could help. Thanks.

#include<stdio.h>
int main(){
    int i, j, k, n;
    // get the size of the square matrices from user
    scanf("%d", &n);

    // allogate memory for the matrices
    int * mul_1 = calloc(n, sizeof(int));
    int * mul_2 = calloc(n, sizeof(int));
    int * mul_3 = calloc(n, sizeof(int));

    //get data from user
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            scanf("%d", mul_1+n*i+j);
        }
    }
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            scanf("%d", mul_2+n*i+j);
        }
    }
    // display matrices
    printf("Entered matrices are:\n =First=\n");
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            printf("%d\t", *(mul_1+n*i+j));
        }
        printf("\n");
    }
    printf("=Second=\n");
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            printf("%d\t", *(mul_2+n*i+j));
        }
        printf("\n");
    }

    //begin matrix multiplicaition
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            int sum = 0;
            for(k=0; k<n; k++){
                int a = *(mul_1 + n*i + k);
                int b = *(mul_2 + n*k + j);
                sum += a*b;
            }
            *(mul_3 + i*n + j) = sum;
        }
    }
    //display results
    printf("Result:\n");
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            printf("%d\t", *(mul_3+n*i+j));
        }
        printf("\n");
    }

    return 0;
}

You don't allocate enough space ( n ) for mul_1 , mul_2 and mul_3 which seems to be n*n matrices.

You can use valgrind to detect this kind of errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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