Reputation: 49
So, I have to use this function from 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.
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?
Upvotes: 2
Views: 1560
Reputation: 32542
The function expects a flat array, e.g., 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.
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:
Upvotes: 2
Reputation: 66244
gsl_matrix_view_array expects your matrix as a contiguous single allocation in row-major order. 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.
Upvotes: 1