From hin-tak.leung at cimr.cam.ac.uk  Mon Nov 20 14:46:45 2006
From: hin-tak.leung at cimr.cam.ac.uk (Hin-Tak Leung)
Date: Mon, 20 Nov 2006 13:46:45 +0000
Subject: [Rd] array indexes in C
In-Reply-To: <20061119150123.GA4592@pu100877.student.princeton.edu>
References: <45607055.7010900@stat.purdue.edu>
	<20061119150123.GA4592@pu100877.student.princeton.edu>
Message-ID: <4561B1C5.1000605@cimr.cam.ac.uk>

Don't think either of you are correct,  because double x[][] is of type 
double ** , (x is a pointer to a pointer/array of doubles), whereas R
passes double() as double * through the .C() interface. So the C code
as written in Ben's message won't work.

numeric()/double() in R are created as single-dimension arrays (or
pointer to type), not arrays of arrays (pointer to pointer to type).

You'll need to do something like this:

void foo(int *ni, int *nj, double *x) {
  x[ (*nj) * i + j ] = ...
/* or the other way round, not very sure about your intention of memory 
layout, in C convention or Fortran convention */
  x[ (*ni) * j + i] = ...

}

Would love somebody to prove me wrong though...

Hin-Tak Leung

Tamas K Papp wrote:
> Hi Ben,
> 
> Thanks for your answer.  I looked at the status of VLA on the GCC
> homepage and it appears to be "broken". [1] Do you think that the code
> below still works?  Or are you using a different compliler?
> 
> Thanks,
> 
> Tamas
> 
> [1] http://gcc.gnu.org/c99status.html
> 
> 
> On Sun, Nov 19, 2006 at 09:55:17AM -0500, Benjamin Tyner wrote:
>> Tamas,
>>
>> You could write convenience functions, but I have used the C99 mechanism 
>> for variable length arrays with no problems calling from R. One thing 
>> you have to keep in mind though is that (as far as I know) the 
>> dimensions must be passed before the array reference. So for example,
>>
>> r <- .C("foo",
>>               as.integer(ni),
>>               as.integer(nj),
>>               x = double(ni * nj),
>>               ...)
>>
>> with your function defined as
>>
>> void foo(int *ni, int *nj, double x[*ni][*nj])
>> {
>> ...
>>
>> Then in C you can access elements of x via x[3][4], for example.
>>
>> Ben
>>
>> ______________________________________________
>> R-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] array indexes in C
Hin-Tak Leung