Wednesday, July 16, 2014

Initialize c array on the heap by copying and iteration through pointer

List initialization syntax cannot be used on the heap (dynamic memory), but there is a workaround: you first initialize on the stack, then copy to the heap:

# c++ code
#include "RcppArmadillo.h"

// via the depends attribute we tell Rcpp to create hooks for
// RcppArmadillo so that the build process will know what to do
//
// [[Rcpp::depends(RcppArmadillo)]]


using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
void testpointer() {
 int xdat[5] = {1, 2, 3, 4, 5};
 int* x = new int[5];
 std::copy(xdat, xdat+5, &x[0]);
 double ydat[5] =  {1.1, 2.2, 3.3, 4.4, 5.5};
 double* y = new double[5];
 std::copy(ydat, ydat+5, &y[0]);

 Rcout << "x0: " << *(x++) << "\n";
 Rcout << "x0: " << *(x++) << "\n";
 Rcout << "x0: " << *(x++) << "\n";
 Rcout << "x0: " << *(x++) << "\n";
 Rcout << "x0: " << *(x++) << "\n";
 Rcout << "y0: " << *(y++) << "\n";
 Rcout << "y0: " << *(y++) << "\n";
 Rcout << "y0: " << *(y++) << "\n";
 Rcout << "y0: " << *(y++) << "\n";
 Rcout << "y0: " << *(y++) << "\n";
}

In R:

> Sys.setenv("PKG_CXXFLAGS"="-std=c++11")
> require(Rcpp)
> sourceCpp("test.cpp")
> testpointer()
x0: 1
x0: 2
x0: 3
x0: 4
x0: 5
y0: 1.1
y0: 2.2
y0: 3.3
y0: 4.4
y0: 5.5

0 comments: