首页 > 解决方案 > 无法为某些特定值填充为矩阵分配的内存

问题描述

所以我制作了这个程序,它创建了 2 个矩阵(m1**,m2**),而不是多个矩阵。但它会随机崩溃一些值(例如:m1[2][1]、m2[2][1];m1[4]m2[3],在最后一个实例中,它在 i choocle m2 值之前中断)。我知道问题发生在分配内存之后,所以可能是在填充矩阵时(preencherMatrix 函数)。我不知道为什么,你能帮帮我吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct
{
    int dX,dY;
    int** mat;
} MATRIX;

MATRIX criarMatrix (MATRIX mat)
{
    int aux;

    printf("MATRIX \n");
    printf("Dimensao X: \n");
    scanf("%d",&aux);
    mat.dX=aux;
    printf("Dimensao Y: \n");
    scanf("%d",&aux);
    mat.dY=(int)aux;

    int index;

    mat.mat=(int**)malloc(mat.dX*sizeof(int*));
        for (index=0;index<mat.dY;index++)
            mat.mat[index]=(int*)malloc(mat.dY*sizeof(int));

    return(mat);
}

MATRIX preencherMatrix (MATRIX mat)
{
    int x,y;

    for(x=0;x<mat.dX;x++)
    {
        for(y=0;y<mat.dY;y++)
        {
            mat.mat[x][y]=rand()%11;
        }
    }
    return(mat);
}

void printMatrix (MATRIX mat)
{
    int x,y;

    printf("\n................... \n");
    for(x=0;x<mat.dX;x++)
    {
        for(y=0;y<mat.dY;y++)
        {
            printf("%d ",mat.mat[x][y]);
        }
    printf("\n");
    }
    printf("................... \n");
}

MATRIX multiplicaMatrix (MATRIX m1, MATRIX m2)
{
    int x,y,i,j;

    x=m1.dX;
    y=m2.dY;

    for(i=0;i<x;i++)
    {
        for(j=0;j<y;j++)
        {
            m1.mat[i][j]=m1.mat[i][j]*m2.mat[j][i];
        }
    }
    return(m1);
}

void main ()
{
    srand(time(NULL));

    MATRIX m1;
    MATRIX m2;

    m1=criarMatrix(m1);
    m1=preencherMatrix(m1);
    printMatrix(m1);

    m2=criarMatrix(m2);
    m2=preencherMatrix(m2);
    printMatrix(m2);

    if (m1.dX!=m2.dY)
    {
        printf("Numero de colunas de M1 e diferente do numero de filas de M2\n \n");
        return(-1);
    }

    m1=multiplicaMatrix(m1,m2);
    printMatrix(m1);
}

标签: c

解决方案


for (index=0;index<mat.dY;index++)1号之后的这条线malloc应该有index < mat.dX

您已经用 分配了第一个维度dX,因此第二个维度的循环应该从0..dX-1


推荐阅读