[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-gsl] Vector and matrix views
From: |
Brian Gough |
Subject: |
Re: [Help-gsl] Vector and matrix views |
Date: |
Thu, 8 Dec 2005 18:07:06 +0000 |
Dimitris Papavasiliou writes:
> Would something like this work
>
> +====
> gsl_vector v; /* a struct, not a pointer */
>
> v = gsl_vector_view_from_array(array, n).vector;
> +====
>
> I know this looks ugly too but hidden behind a macro it would be ok.
> Would this work correctly?
This is ok in principle. What you don't want to do is
gsl_vector *v;
v = &gsl_vector_view_from_array(array, n).vector;
which is easily confused with it and causes invalid memory accesses
(since the contents of the vector struct disappears from the stack
immediately after the expression is evaluated).
I use the style "&view.vector" to avoid this problem. Every vector is
always a pointer and every view is always on the stack, so everything
stays consistent. A useful macro is &(x).vector.
As James mentions you can construct a vector directly (or define a
small inline function to do it). This works for non-const vectors. I
do use it myself, it is alright.
> On a side note: why do views have a separate struct with only one
> member? I've read in an old message in the archive that this is so in
> order to make const vectors work but I can't imagine how keeping a
> struct with one member is any different than keeping the member itself.
> If it is't too much trouble could someone please explain?
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.
--
Brian Gough
Network Theory Ltd,
Publishing the GSL Manual --- http://www.network-theory.co.uk/gsl/manual/