当我在第一个矩阵中使用malloc
fucntion时。它没有给出正确的价值。但没有malloc
它会给出正确答案。任何人都可以告诉我,当我使用malloc
并创建矩阵并将它们存储在连续的位置时,会出现什么错误?
/* Calling DGELS using row-major order */
#include <stdio.h>
#include <lapacke.h>
#include <conio.h>
#include <malloc.h>
int main ()
{
// double a[6][2] = {{1,2},{1,4},{1,6},{1,8},{1,10},{1,12}};
//double outputArray[3][1];
int designs=6;
double **a;
int i,j,d,i_mal;
lapack_int info,m,n,lda,ldb,nrhs;
//double outputArray[6][1] = {{2},{4},{4},{5},{5},{7}};
double **outputArray;
a=(double**)malloc(6* sizeof(double*));
for (i=0;i<6;i++)
{
a[i]=(double*)malloc(2* sizeof(double));
}
//for storing them on particular places
for (i=0;i<6;i++)
{
for(j=0;j<2;j++)
{
outputArray[i]=&outputArray[j][i];
}
}
//putting values
for (i=0;i<6;i++)
{
for(j=0;j<2;j++)
{
printf("put a[%d][%d]",i,j);
scanf("%lf",&a[i][j]);
}
}
outputArray = (double**) malloc(6* sizeof(double*));
outputArray[0]=(double*) malloc(6* sizeof(double));
for (i=0;i<designs;i++)
{
outputArray[i]=&outputArray[0][i];
}
for (i=0;i<6;i++)
{
printf("put first value");
scanf("%lf",&outputArray[i][0]);
}
m = 6;
n = 2;
nrhs = 1;
lda = 2;
ldb = 1;
info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*outputArray,ldb);
printf("\n coefficients are:");
for(i=0;i<n;i++)
{
for(j=0; j < nrhs; j++)
{
printf("%lf ",outputArray[i][j]);
}
printf("\n");
}
getch();
return (info);
}
答案 0 :(得分:0)
根据using malloc in dgels function of lapacke的回答,您可以对矩阵a
使用相同的技巧:
double** a=malloc(m*sizeof(double*));
if(a==NULL){printf("malloc failed\n");}
a[0]=malloc(m*n*sizeof(double));
if(a[0]==NULL){printf("malloc failed\n");}
for (i=0;i<m;i++){
a[i]=&a[0][i*n];
}
完整代码,包括释放内存的free
:
/* Calling DGELS using row-major order */
#include <stdio.h>
#include "lapacke.h"
//#include <conio.h>
#include <malloc.h>
int main ()
{
//double a[3][2] = {{1,0},{1,1},{1,2}};
double **outputArray;
int designs=3;
int i,j,d,i_mal;
lapack_int info,m,n,lda,ldb,nrhs;
m = 3;
n = 2;
nrhs = 4;
lda = n;
ldb = nrhs;
//double outputArray[3][1] = {{6},{0},{0}};
double** a=malloc(m*sizeof(double*));
if(a==NULL){printf("malloc failed\n");}
a[0]=malloc(m*n*sizeof(double));
if(a[0]==NULL){printf("malloc failed\n");}
for (i=0;i<m;i++){
a[i]=&a[0][i*n];
}
a[0][0]=1;
a[0][1]=0;
a[1][0]=1;
a[1][1]=1;
a[2][0]=1;
a[2][1]=2;
outputArray = malloc(m* sizeof(double*));
if(outputArray==NULL){printf("malloc failed\n");}
outputArray[0]=malloc(m*nrhs* sizeof(double));
if(outputArray[0]==NULL){printf("malloc failed\n");}
for (i=0;i<m;i++){
outputArray[i]=&outputArray[0][i*nrhs];
}
for (i=0;i<m;i++)
{
printf("put first value");
scanf("%lf",&outputArray[i][0]);
}
info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*outputArray,ldb);
for(i=0;i<n;i++)
{
for(j=0;j<nrhs;j++)
{
printf("%lf ",outputArray[i][j]);
}
printf("\n");
}
//getch();
free(a[0]);
free(a);
free(outputArray[0]);
free(outputArray);
return (info);
}