[Rd] Confusion regarding allocating Matrices.
bates at stat.wisc.edu
Fri Oct 23 16:23:06 CEST 2009
On Fri, Oct 23, 2009 at 8:39 AM, Abhijit Bera <abhibera at gmail.com> wrote:
> I'm having slight confusion.
> I plan to grow/realloc a matrix depending on the data available in a C
> Here is what I'm tried to do:
> SEXP Data;
Those lines should be in the other order, shouldn't they?
Also, you need to PROTECT Data or bad things will happen.
> printf("%f %f\n\n\n\n",REAL(Data),REAL(Data));
> Here is my confusion:
> Do I always require to allocate the exact number of data elements in a R
> In the above code segment I have clearly exceeded the number of
> elements that have been allocated but my program doesn't crash.
Remember that when programming in C you have a lot of rope with which
to hang yourself. You have corrupted a memory location beyond that
allocated to the array but nothing bad has happened - yet.
> I don't find any specific R functions for reallocation incase my data set
> grows. How do I reallocate?
You allocate a new matrix, copy the contents of the current matrix to
the new matrix, then release the old one. It gets tricky in that you
should unprotect the old one and protect the new one but you need to
watch the order of those operations.
This approach is not a very good one. If you really need to grow an
array it is better to allocate and reallocate the memory within your C
code using calloc and realloc then, at the end of the calculations,
allocate an R matrix and copy the results over.
Also, you haven't said whether you are growing the matrix by row or by
column or both. If you are adding rows then you can't just reallocate
storage because R stores matrices in column-major order. The positions
of the elements in a matrix with n+1 rows are different from those in
a matrix with n rows.
> Is it necessary to reallocate or is R handling
> the memory management for the matrix that I have allocated?
> Abhijit Bera
> [[alternative HTML version deleted]]
> R-devel at r-project.org mailing list
More information about the R-devel