I'm studying Rcpp and encountered an interesting but (might be) weird issue.
Essentially int *a = new int(1);
is not working in the same way as:
int b = 1;
int *a;
a = &b;
Any ideas why? Full code below. If I uncomment int *a = new int(1);
then the code below works as intended.
#include <Rcpp.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
int bar(SEXP a) {
Rcpp::XPtr<int> ptr(a);
int b = *ptr;
cout << b;
return (b);
}
// [[Rcpp::export]]
SEXP foo() {
// int *a = new int(1);
int b = 1;
int *a;
a = &b;
cout << *a;
Rcpp::XPtr<int> ptr(a);
return ptr;
}
Then in R: I was hoping to get b = 1
.
> a = foo()
1
> b = bar(a)
0
> b
[1] 0
=========================================================================== Edit: My question actually originates from Pass a c++ object as a pointer an reuse in another function in Rcpp, but when I wish to test c-style pointer below
int b = 1;
int *a;
a = &b;
to replace int *a = new int(1);
, it's simply not working as intended. That's why I asked this question here.