From dmbates at gmail.com  Mon Jun 20 03:03:43 2005
From: dmbates at gmail.com (Douglas Bates)
Date: Sun, 19 Jun 2005 20:03:43 -0500
Subject: [Rd] 1-based arrays and copying vectors
In-Reply-To: <32898.70.59.24.172.1119221601.squirrel@webmail.fpcc.net>
References: <32898.70.59.24.172.1119221601.squirrel@webmail.fpcc.net>
Message-ID: <40e66e0b05061918035a3ace06@mail.gmail.com>

On 6/19/05, Rob Lopaka Lee <rlee at inverness.fpcc.net> wrote:
> I'm interfacing to C code that uses 1-based indexing on arrays -- it
> ignores the zeroth element.  Thus, input vectors from R must be moved up
> one, and output arrays must be moved down one.
> 
> What is the best way to deal with this using R internal code?

If the C code can be relied upon to ignore the zero'th element of the
array then write a wrapper that gets the array, say int v[], from R
and passes &v[-1] to your C code.  That has the effect of shifting all
the addresses back by one position.
 
> My current approach is:
> 
> For an input R vector of length n, allocate a new vector(v) of length n+1
> and copy input into v[1] to v[1+n].  Call with new vector.
> 
> For an output array(a) of length n, allocate a new vector of length n-1
> and copy a[1] to a[n] into v[0] to v[n-1].
> 
> If this is the best approach, is there an idiom for copying vectors?

In C you could use the memcpy function or the Memcpy macro defined in
<R_ext/RS.h>.



[Rd] 1-based arrays and copying vectors
Douglas Bates