[Rd] 1-based arrays and copying vectors
Douglas Bates
dmbates at gmail.com
Mon Jun 20 03:03:43 CEST 2005
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>.
More information about the R-devel
mailing list