[R] Newbie problems with R and compiled C

Eusebio Arenal Gutiérrez use at eio.uva.es
Tue Dec 18 13:21:02 CET 2001


I'm a beginer programming C and I have the following problem:

I have the following C-code file

#include <stdlib.h>

void gen(int *n,  int *a, int *c, int *m, int *x0, int *x);

main(){
  int nn = 31;
  int aa = 3;
  int cc = 0;
  int mm = 31;
  int xx0 = 9;
  int xx[nn];
  int i;
  gen(&nn,&aa,&cc,&mm,&xx0,xx);
  for (i = 0; i <= nn-1; i++)
    printf("%d ,",xx[i]);
  printf("\n %d",nn);
  printf("\n %d",aa);
  printf("\n %d",cc);
  printf("\n %d",mm);
  printf("\n %d",xx0);
}

void gen(int *n,  int *a, int *c, int *m, int *x0, int *x){
  int i;
  x[0]=*x0;
  for (i = 1; i <= *n-1; i++)
    x[i] = (*a * x[i-1] + *c) % *m;
}

I compile it with:

gcc gen2.c -o gen2.exe (Within emacs in W2000)

and executing gen2.exe the result is the correct one:

9 ,27 ,19 ,26 ,16 ,17 ,20 ,29 ,25 ,13 ,8 ,24 ,10 ,30 ,28 ,22 ,4 ,12 ,5 ,15
,14 ,
11 ,2 ,6 ,18 ,23 ,7 ,21 ,1 ,3 ,9 ,
 31
 3
 0
 31
 9

Then I put in a library with files:

#include <stdlib.h>

void gen(int *n,  int *a, int *c, int *m, int *x0, int *x){
  int i;
  x[0] = *x0;
  for (i = 1; i <= *n-1; i++)
    x[i] = (*a * x[i-1] + *c) % *m;
}

for the code and the wrapper function:

gen <- function(n, a, c, m, x0){
  .C("gen", x=integer(n),
          n=as.integer(n),
          a=as.integer(a),
          c=as.integer(c),
          m=as.integer(m),
          x0=as.integer(x0))
}

and the result is not the desired one:

> gen(n=31, a=3, c=0, m=31, x0=9)
$x
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

$n
[1] 31

$a
[1] 3

$c
[1] 0

$m
[1] 31

$x0
[1] 31

In fact $x shouldn't be 0 and $x0 should be 9.

I think I'm missing something obvious with C and R.

Thanks for any hint,

Eusebio Arenal




-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list