From ripley at stats.ox.ac.uk  Fri Apr 15 08:26:46 2005
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Fri Apr 15 08:26:55 2005
Subject: [Rd] dynamic array output by .C
In-Reply-To: <92FD2DE5-0622-464B-BFF5-AA66881CD0E5@r-project.org>
References: <58618a6205041414062f07d2a8@mail.gmail.com>
	<Pine.LNX.4.61.0504142212070.14473@gannet.stats>
	<58618a62050414150165aae64@mail.gmail.com>
	<92FD2DE5-0622-464B-BFF5-AA66881CD0E5@r-project.org>
Message-ID: <Pine.LNX.4.61.0504150721340.19992@gannet.stats>

On Thu, 14 Apr 2005, Simon Urbanek wrote:

> On Apr 14, 2005, at 6:01 PM, Tib wrote:
>
>> from the examples of Writing R Extensions,  I see one still has to
>> declare the size of arrays by NEW_NUMERIC(n) or
>> allocVector(REALSXP,n), how can I extend arrays?
>
> AFAIR you cannot extend vectors - it's like in C, you cannot extend allocated 
> memory without changing the pointer (i.g.). In order to get a vector of a 
> different size, you have to allocate a new one and copy the common contents. 
> If you are concerned about efficiency, why don't you just use arbitrary large 
> vectors and pass along the number of used elements? Then you can easily add 
> elements without re-allocating and just return the number of elements used 
> after the operation. That way you can control the probability of having to 
> allocate a new vector, possibly making it zero.

That's not a particularly good idea, as R keeps the length in the vector.
There is a way to do this, lengthgets().  That shortens vectors in one 
case, and reallocates and copies contents if extending.  Quite a lot of 
internal code does use long vectors and call lengthgets() at the end to 
shorten them to the right size.  (Other code duplicates that in 
lengthgets.)

As the name implies, this is the internal form of length(x) <- value.

Yes, it does change the pointer because it creates (potentially a new 
object).  But since an R object is just a few parameters (e.g. type and 
length) and a pointer, you could in fact extend an R vector `in place'.

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595


[Rd] dynamic array output by .C
Prof Brian Ripley