Skip to content

Values added to a vector with push_back cannot be used immediately #453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
pepijn-devries opened this issue Apr 26, 2025 · 1 comment
Open

Comments

@pepijn-devries
Copy link

I'm using a writable::integers to store results in an iterative process, where I want to use elements from the vector of integers in the process and update them. However, when I push_back() a value to the vector, and then immediately check its value I will get some random number. Weirdly, when the vector is returned to R it seems to look fine. It is illustrated in the reprex below where I print the value that I just pushed back to the vector.

Am I doing something wrong?

library(cpp11)
#> Warning: package 'cpp11' was built under R version 4.3.3

cpp_function("
writable::integers test() {
    writable::integers x((R_xlen_t)0);
    for (int i = 0; i < 10; i++) {
      x.push_back(i);
      Rprintf(\"When I want to us the integer x[i], I get %i instead of %i\\n\", x[i], i);
    }
    return x;
  }
")

test()
#> When I want to us the integer x[i], I get -1107622224 instead of 0
#> When I want to us the integer x[i], I get -1107622224 instead of 1
#> When I want to us the integer x[i], I get -1107622224 instead of 2
#> When I want to us the integer x[i], I get -1107622224 instead of 3
#> When I want to us the integer x[i], I get -1107622224 instead of 4
#> When I want to us the integer x[i], I get -1107622224 instead of 5
#> When I want to us the integer x[i], I get -1107622224 instead of 6
#> When I want to us the integer x[i], I get -1107622224 instead of 7
#> When I want to us the integer x[i], I get -1107622224 instead of 8
#> When I want to us the integer x[i], I get -1107622224 instead of 9
#>  [1] 0 1 2 3 4 5 6 7 8 9

Created on 2025-04-26 with reprex v2.0.2

@pepijn-devries
Copy link
Author

pepijn-devries commented Apr 28, 2025

It turns out that I had to cast x[i] to int explicitly. After that correction, the code above works as expected. Here is the corrected code:

library(cpp11)

cpp_function("
writable::integers test() {
    writable::integers x((R_xlen_t)0);
    for (int i = 0; i < 10; i++) {
      x.push_back(i);
      Rprintf(\"When I want to us the integer x[i], I get %i which is the same as %i\\n\", (int)x[i], i);
    }
    return x;
  }
")

test()

Why is this explicit cast needed, and is this documented anywhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant