首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

麻烦各位前辈进来帮小弟我找下异常-关于建立一个矩阵

2013-11-11 
麻烦各位前辈进来帮我找下错误-关于建立一个矩阵利用malloc函数动态构建一个矩阵,例如建立2x2的矩阵,编译

麻烦各位前辈进来帮我找下错误-关于建立一个矩阵
利用malloc函数动态构建一个矩阵,例如建立2x2的矩阵,编译没有错误,但在输入4个整数后,想显示所建立的矩阵,程序报错。代码如下

//动态构建一矩阵

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

int *getData(int i,int col);
void printData(int **p,int row,int col);

void main()
{
int **p;
int row,col,i;

printf("Input the rows of the matrix:");//输入矩阵的行数
scanf("%d",&row);

printf("Input the cols of the matrix:");//输入矩阵的列数
scanf("%d",&col);

printf("\n");

if(row<=0||col<=0)
return;

//动态建立矩阵;
p=(int **)malloc(row * sizeof(int *));

if(p==NULL)
{
printf("Insufficient memory available!\n");
return;
}

//输入数据;
for(i=0;i<row;i++)
{
p[i]=getData(i,col);

if(p[i]=NULL)
{
printf("No enough memory!\n");
freeMemory(p,row);
return;
}
}

printf("\n");

//显示矩阵的各元素;
printf("The matrix as followings:\n");
printData(p,row,col);
}

int *getData(int i,int col)
{
int *p;
int j;

p=(int *)malloc(col*sizeof(int));

if(p==NULL)
{
printf("No enough memory!\n");
return (NULL);
}

for(j=0;j<col;j++)
{
printf("Input matrix[%d][%d]:",i+1,j+1);
scanf("%d",&p[j]);
}

return (p);
}

void printData(int **p,int row,int col)
{
int i,j;

for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%5d",p[i][j]);

printf("\n");
}
}


[解决办法]


if(p[i]=NULL)  //////p[i] = NULL 确定不是  p[i] == NULL
{
printf("No enough memory!\n");
freeMemory(p,row);
return;
}


热点排行