[英]Dynamically Allocation and GSL(Gnu Scientific Library)
So, I have to use this function from GSL. 因此,我必须使用GSL的此功能。 This one:
这个:
gsl_matrix_view_array (double * base, size_t n1, size_t n2)
The first argument ( double * base
) is the matrix I need to pass to it, which is read as input from the user. 第一个参数(
double * base
)是我需要传递给它的矩阵,该矩阵作为用户的输入读取。
I'm dynamically allocating it this way: 我以这种方式动态分配它:
double **base;
base = malloc(size*sizeof(double*));
for(i=0;i<size;i++)
base[i] = malloc(size*sizeof(double));
Where size is given by the user. 尺寸由用户指定。 But then, when the code runs, it warns this :
但是,当代码运行时,它会发出警告:
"passing arg 1 of gsl_matrix_view_array from incompatible pointer type".
What is happening? 怎么了?
The function expects a flat array, eg, double arr[size*size];
该函数需要一个平面数组,例如
double arr[size*size];
. 。
Here's an example from the documentation that I have slightly modified to use a matrix view: 这是文档中的一个示例,我对其进行了稍微修改以使用矩阵视图:
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
int main(void) {
int i, j;
double *arr = malloc(10 * 3 * sizeof*arr);
gsl_matrix_view mv = gsl_matrix_view_array(arr, 10, 3);
gsl_matrix * m = &(mv.matrix);
for (i=0; i<10; i++)
for (j=0; j<3; j++)
gsl_matrix_set(m, i, j, 0.23 + 100*i + j);
for (i=0; i<10; i++)
for (j=0; j<3; j++)
printf("m(%d,%d) = %g\n", i, j, gsl_matrix_get(m, i, j));
free(arr);
return 0;
}
Note that you can also directly allocate memory for the matrix using the provided API. 请注意,您还可以使用提供的API为矩阵直接分配内存。
Here's the original example: 这是原始示例:
#include <stdio.h>
#include <gsl/gsl_matrix.h>
int main(void)
{
int i, j;
gsl_matrix * m = gsl_matrix_alloc(10, 3);
for (i=0; i<10; i++)
for (j=0; j<3; j++)
gsl_matrix_set(m, i, j, 0.23 + 100*i + j);
for (i=0; i<10; i++)
for (j=0; j<3; j++)
printf("m(%d,%d) = %g\n", i, j, gsl_matrix_get(m, i, j));
gsl_matrix_free(m);
return 0;
}
For reference: 以供参考:
gsl_matrix_view_array expects your matrix as a contiguous single allocation in row-major order. gsl_matrix_view_array期望矩阵以行优先的顺序作为连续的单个分配。 You should be allocating your array like this:
您应该像这样分配数组:
double (*ar)[size] = malloc(sizeof(ar[size]) * size);
Then (after populating it) 然后(填充后)
gsl_matrix_view_array(ar[0], size, size);
Finally, free your allocation when done with a single call: 最后,只需一次调用即可释放您的分配:
free(ar);
Note: Don't try this with C++, as VLA's aren't standard-supported for that language. 注意:请勿在C ++中尝试此操作,因为该语言不标准支持VLA。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.