bug-gsl
[Top][All Lists]
Advanced

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

Re: [Bug-gsl] Gsl_vector_const_view


From: Brian Gough
Subject: Re: [Bug-gsl] Gsl_vector_const_view
Date: Tue, 05 Dec 2006 20:51:16 +0000
User-agent: Wanderlust/2.14.0 (Africa) Emacs/21.3 Mule/5.0 (SAKAKI)

At Mon, 4 Dec 2006 17:21:09 -0800,
Leibs, Jeremy wrote:
> I think the way const's are dealt with in gsl_vector_views (and matrix
> views) is possibly flawed.  If it's not flawed I'm missing something
> fundamental in the way they are intended to  be used.

Hello,

Thanks for your email.  You're correct that the const does not protect
the data, only the struct.  Ideally it would protect the data as well
but I couldn't find a reasonable way to do that.

Originally I tried having a const inside the struct, similar to your
example, but it made the const and non-const versions of the
gsl_vector type incompatible.

This meant that it wasn't possible to have functions which accepted
both const and non-const vectors, as it would be for normal C library
functions (e.g. strlen).  I was surprised that it was not possible but
could not find any way round it in the C standard.  A simple program
which shows the problem is attached below. 

So the best scheme that I could come up with was the current one,
which protects const vectors from being passed to gsl functions that
would modify them, if not from direct modification.

-- 
Brian Gough
(GSL Maintainer)

Network Theory Ltd,
Commercial support for GSL --- http://www.network-theory.com/gsl/


#include <stdlib.h>
#include <stdio.h>

typedef struct {
  size_t n;
  double * data;
} vec;

typedef struct {
  size_t n;
  const double * data;
} cvec;

double 
sum (cvec * v)
{
  double sum = 0.0;
  size_t i, n = v->n;

  for (i = 0; i<n; i++)
    {
      sum += v->data[i];
    }
  return sum;
}

int 
main (void)
{
  double a[3] = {1.0, 2.0, 3.0};
  const double ca[3] = {1.0, 2.0, 3.0};
  vec v;
  cvec cv; 
  
  v.n = 3;
  v.data = a;

  cv.n = 3; 
  cv.data = ca;

  printf("sum of v = %g\n", sum(&v));
  printf("sum of cv = %g\n", sum(&cv));
  return 0;
}

$ gcc -ansi -g vectest.c
vectest.c: In function 'main':
vectest.c:41: warning: passing argument 1 of 'sum' from incompatible pointer 
type




reply via email to

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