Skip to content
Prev 3469 / 10988 Next

[Rcpp-devel] strange code problem

Hi David,

Interesting problem.

You'll find that if you change how you initialize your `res` vector,
you will sidestep this problem, eg. from this:

    NumericVector res(x);

to:

    NumericVector res(A.size());

Why? Because in your original instantiation, as you "save" your
results in `res`, you are trampling over your input.

Here's a short example:

R> s2 = "
  NumericVector x(x_);
  x[0] = 100;
  return x;
"

R> f <- cxxfunction(signature(x_ = "numeric"), body = s2, plugin="Rcpp")
R> x <- c(0.5, 1.0, 2.0)
R> f(x)
## [1] 100   1   2

## But look, we also changed x!
R> x
## [1] 100   1   2

## Now try again with this `x`, and ask yourself why the outcome is different
R> x <- 1:5
R> f(x)
## [1] 100   2   3   4   5

R> x
[1] 1 2 3 4 5

Welcome to the wild west.

HTH,
-steve
On Wed, Feb 15, 2012 at 1:09 PM, Carslaw, David <david.carslaw at kcl.ac.uk> wrote: