#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
int i,j;
void display_matrix(int matrix[],int rows,int colombs){
for(i=0;i<rows;i++){
for(j=0;j<colombs;j++)
printf("%5d ",matrix[i*rows+j]);
printf("\n");
}
}
int *create_matrix(int rows,int colombs,int min,int max){
int *matrix=NULL;
matrix=(int*)calloc(colombs*rows,sizeof(int));
for(i=0;i<rows;i++)
for(j=0;j<colombs;j++)
matrix[i*rows+j]=(rand()%(max-min+1))+min;
return matrix;
}
int main(){
int *m=NULL,row,col;
do{
printf("Give the number of rows:\n");
scanf("%d",&row);
}while(row<=0);
do{
printf("Give the number of colombs:\n");
scanf("%d",&col);
}while(col<=0);
m=create_matrix(row,col,10,99);
display_matrix(m,row,col);
return 0;
}
矩阵按预期显示,但程序返回值为 3221226356。我尝试更改函数 create_matrix() 中的行和列,返回值为 0,但矩阵有垃圾数据。
您似乎使用的是 Windows。
在 Windows 上,错误代码
3221226356
(十六进制为 0xc0000374
)表示堆损坏。
损坏是由于在无效索引处访问您的
matrix
而引起的。
您的错误在于将行和列索引转换为
matrix
中的索引。
代替:
i*rows+j
i*colombs+j
您在 2 个地方遇到此错误:
display_matrix
中):
printf("%5d ",matrix[i*rows+j]);
create_matrix
中):
matrix[i*rows+j]=(rand()%(max-min+1))+min;
旁注:
colombs
可能应该重命名为colomns
。