c - 无法为某些特定值填充为矩阵分配的内存
问题描述
所以我制作了这个程序,它创建了 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);
}
解决方案
for (index=0;index<mat.dY;index++)
1号之后的这条线malloc
应该有index < mat.dX
。
您已经用 分配了第一个维度dX
,因此第二个维度的循环应该从0..dX-1
推荐阅读
- modelsim - 无法在 modelsim 中创建项目
- android-studio - 如何在android的新活动中转换片段?
- swift - 有没有办法在 Swift 中延迟返回语句?
- python - 美丽的汤有时返回 NoneType
- python - Python 熊猫 .transform
- c# - 我可以更改列表的显示方式,但在自定义编辑器中保留 Add(-) 和 Remove(+) 按钮吗?
- node.js - 在 Node.js 中为数组的每个元素编写一个文件
- java - 使用 Streams 直接将属性转换为 HashMap
- c - 从递归函数打印主函数
- c++ - 如何重新映射 YUY2 图像?