简体   繁体   English

当提供来自 R 的向量时,C 中的 For 循环不返回预期的 output

[英]For loop in C not returning expected output when provided a vector from R

So I have a functioning loop below that I can compile and execute happily in C++.所以我在下面有一个功能循环,我可以在 C++ 中愉快地编译和执行。

#include <iostream >
using std::cout;
using std::endl;
int main()
{
    int x[] = { 1, 2, 3, 10, 3, 2 };
    int j = 6;
    double highest = 0;
    double position = 0;
    for (int i = 0; i < j; i++) {
        if (x[i] > highest) {
            highest = x[i];
            position = i;
        }
    }
    cout << position;
    cout << endl;
    cout << highest;
    return 0;
}

However when I try to turn this into a function that I can call from R, the position and highest values dont seem to update from the 'for' loop.但是,当我尝试将其转换为可以从 R 调用的 function 时,position 和最高值似乎不会从“for”循环中更新。 I am sure it has something to do with pointers but cant for the life of me figure it.我确信它与指针有关,但我一生都无法理解它。 Any help would be appreciated.任何帮助,将不胜感激。

Note that we cant use RCPP for this task and have to use extern "C" {}请注意,我们不能在此任务中使用 RCPP,必须使用 extern "C" {}

#include <R.h>
extern "C" {

void whichmax(double* x, int* len)
{
    double highest = 0;
    double position = 0;
    for (int i = 0; i < *len; i++) {
        if (x[i] > highest) {
            highest = x[i];
            position = i;
        }
    }
    Rprintf("please work %f \n", highest);
    Rprintf("please work %f \n", position);
}
}

Code used in R to run the function R 中用于运行 function 的代码

dyn.load("whichmax.dll")

x <- c(1,2,2,8,4,8)

.C("whichmax",x, length(x))

dyn.unload("whichmax.dll")

Thanks in advance for an assistance!提前感谢您的帮助!

Figured it out.弄清楚了。

The problem was actually in the R code, I had to force the input 'len' value to be an integer and it all ran just fine.问题实际上出在 R 代码中,我不得不强制输入 'len' 值为 integer 并且一切运行良好。

dyn.load("whichmax.dll")

x <- c(1,2,2,8,4,8)

.C("whichmax",x, as.integer(length(x)))

dyn.unload("whichmax.dll")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM