繁体   English   中英

一个数组的最后一个元素被下一个数组的第一个元素覆盖

[英]Last element of one array overwritten by first element of the next array

我一直在研究涉及两个矩阵相乘的问题,我必须从用户那里获取元素。 但是,在获取元素时(当我打印它们时),第一个矩阵的最后一个元素等于第二个矩阵的第一个元素。 结果我没有得到正确的结果。 如果有人可以帮我,我有义务。 谢谢。

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

您没有为mul_1mul_2mul_3似乎是n*n矩阵的足够空间( n )。

您可以使用valgrind来检测此类错误。

暂无
暂无

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

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