help-gsl
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-gsl] Vector and matrix views


From: Dimitris Papavasiliou
Subject: Re: [Help-gsl] Vector and matrix views
Date: Thu, 08 Dec 2005 21:09:43 +0200
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050513 Debian/1.7.8-1

Brian Gough wrote:

In C a const object has to be initialised in a single step (because
you can't modify it afterwards).  And initialisers can only contain
constants, not expressions.  So to create a const object whose members
depend on other variables you have to go through an indirection --
create a non-const object first, then make it const.  That is where
the struct comes from.  It's const on the outside but non-const on the
inside.

It would be cool to discover other ways to do it but I think that this
might be the only way in C.
Are you sure about that constant initialiser part? That is necessary with "static" variables and for good reason: the intial values of static vars (which live in the heap) are written into the data section of the executable at compile time. Therefore the compiler has to know what to write.

But the same shouldn't hold for const vars, unless I'm getting the whole thing wrong. If I understand you correctly and you just want a function that returns "const gsl_vector" from an array then wouldn't this work:

+====8<== cut here ==8<====

#include <gsl/gsl_vector.h>

const gsl_vector _gsl_vector_const_view_array(double *BASE, int n)
{
   const gsl_vector v = {n, 1, BASE, NULL, 0};

   return v;
}

int main()
{
   double v_c[3] = {1, 2, 3};
   const gsl_vector v_g = _gsl_vector_const_view_array(v_c, 3);

   gsl_vector_fprintf(stdout, &v_g, "%f");

   /* uncomment this to make sure the compiler will complain */
   /* v_g.data = NULL; */
exit (0);
}

+====8<== cut here ==8<====

I'm not sure wherher I can/should attach this so I'm sending this in-line. Just cut and paste it into a file, say foo.c and compile with something along the lines of

gcc -ansi foo.c `gsl-config --cflags --libs`

in UNIX. I've included the -ansi switch to gcc to make sure it won't work just because of some GNU extension. This works as expected (or at least as I expected) and is functionally equivalent to the standard gsl function. The only difference is the absence of the buffering struct.

Am I missing sometinhg?

Dimitris P.

PS: Thanks for the tip James!  It certainly looks better than my approach.





reply via email to

[Prev in Thread] Current Thread [Next in Thread]