【发布时间】:2016-04-22 13:47:33
【问题描述】:
以下代码应将一个矩阵复制到另一个矩阵中。但我得到一个分段错误:核心转储。 xmalloc 函数分配数组,init 初始化它,copy 复制它,xfree 释放空间。我认为我使用 memcpy 的方式是错误,我该如何解决?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int xmalloc(int **p, int dim1, int dim2);
void xfree(int **p, int dim1);
void init(int **p, int dim1, int dim2);
void copy(int **source, int **destination, int dim1, int dim2);
int main(void)
{
int **p1, **p2, dim1, dim2;
scanf("%d\n%d",&dim1,&dim2);
if(!xmalloc(p1,dim1,dim2))
return -1;
if(!xmalloc(p2,dim1,dim2))
return -1;
init(p1,dim1,dim2);
copy(p1,p2,dim1,dim2);
xfree(p1,dim1);
xfree(p2,dim2);
return 0;
}
int xmalloc(int **p, int dim1, int dim2)
{
int i;
p=malloc(dim1*sizeof(int*));
if(p==NULL)
{
perror("Malloc");
return 0;
}
for(i=0; i<dim1; i++)
{
p[i]=malloc(dim2*sizeof(int));
if(p[i]==NULL)
{
perror("Malloc");
return 0;
}
}
return 1;
}
void xfree(int **p, int dim1)
{
int i;
for(i=0; i<dim1; i++)
free(p[i]);
free(p);
}
void init(int **p, int dim1, int dim2)
{
int i, j;
for(i=0; i<dim1; i++)
for(j=0; j<dim2; j++)
p[i][j]=i*dim2+j;
}
void copy(int **source, int **destination, int dim1, int dim2)
{
int i;
for(i=0; i<dim1; i++)
{
memcpy(destination[i],source[i],dim2*sizeof(int));
}
}
什么是错误? 请允许我使用 scanf 来简化这个程序。
解决方案:
-三重指针的使用
-将正确的参数传递给 xfree
【问题讨论】: