2012-02-28 19 views
1

我對C很新,但知道我的方式[R]。這個錯誤可能是C中一個非常愚蠢的錯誤。我的C代碼確實內核平滑。在[R]函數中捕獲了段錯誤

* 當我註釋掉代碼的最後一行時,我的函數有效:results [i] = v; *

此呼叫殺死R:

new.y < -zsmooth2(X = C(0:80000),xpts = DAT $ V2,ypts = DAT $ V4,H = 10000)

*捉住段錯誤* 地址0x1184f8000,原因 '存儲器未被映射'

回溯: 1:.C( 「kernel_smooth」,as.double(X),as.double(YP ts),as.double(xpts),as.integer(n),as.integer(nxpts),as.double(h),result = double(length(xpts))) 2:zsmooth2(x = c 0:80000),xpts = DAT $ V2,ypts = DAT $ V4,H = 10000)

C代碼:

#include <R.h> 
#include <Rmath.h> 
#include <stdio.h> 


void kernel_smooth(double *x, double *ypts, double *xpts, int *n, int *nxpts, double *h, double *results){ 
    int i, j; 

    for(i = 0; i < *n; i++){ 

     double nsum = 0; 
     double dsum = 0; 

     double z = x[i] + *h; 
     double y = x[i] - *h; 

     for(j = 0; j < *nxpts; j++){ 

      if(xpts[j] < y){ 
       continue; 
      } 
      if(xpts[j] > z){ 
       break; 
      } 
      double d = (xpts[j] - i)/*h; 
      double r = dnorm(d, 0, 1, 0); 
      nsum += r * ypts[j]; 
      dsum += r; 
     } 
      Rprintf("test:i %d\n", i); 
      double v = nsum/dsum; 
      Rprintf("test:v %f\n", v); 

     results[i] = v; 
    } 

} 

R-代碼:

dyn.load("~/github/ZevRTricks/smoother1.so") 
zsmooth2<-function(x, ypts, xpts, h){ 
    n <- length(x) 
    nxpts <- length(xpts) 
    dens <- .C("kernel_smooth", as.double(x), as.double(ypts), 
       as.double(xpts), as.integer(n), as.integer(nxpts), 
       as.double(h), result = double(length(xpts))) 
dens[["result"]] 
} 
+0

你有C代碼張貼在C#論壇中.. – MethodMan 2012-02-28 18:00:59

+0

C和C#是兩種完全不同的語言。你不只是交替使用他們的名字。 – BoltClock 2012-02-28 18:04:55

+0

據我所知,你不能輕易地使用C#與R所以代碼真的C? – 2012-02-28 18:22:00

回答

2

xpts and ypts是向量,並且在您的C代碼中,您嘗試訪問其中每個元素的元素1到nnx的長度,在第二個示例中比第一個示例長100倍。比較seq(from = 0, to = 80000 by = 100)0:80000,(並且當你在它時,你可以從0:80000附近刪除c())。

所以我想這xptsypts至少801元長,但低於80001元。你已經搞亂了你的索引。

還要注意,您將x傳遞給您的C代碼,但實際上並未將其用於任何事情。

+0

還沒有測試過,但我確定你是正確的。請問我該如何返回一個索引(對於一個數組),其值大於x且小於y? – 2012-02-28 21:11:42

+0

如果你在談論C語言中的for循環,就像'for(i = x; i Tyler 2012-02-28 21:37:49

+0

感謝您的幫助,但在修復我的代碼後仍然捕獲錯誤。我在上面更新了它。 – 2012-03-01 04:06:10