NumericMatrix:为什么我可以索引超出其维度而不会出错?

NumericMatrix: why can I index beyond its dimensions without error?

我有 R 代码将 matrix() 对象传递给参数为 NumericMatrix 的 Rcpp 函数。 C++ 函数给出了正确的维度,但我也可以在其维度之外对 NumericMatrix 进行索引而不会出错。为什么会这样?下面的 MWE(在 RStudio 中创建的一个 .cpp 文件)后跟一个我看到的输出实例,其中第三行显然是(?)从数组边界外的内存中读取。

#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void myFn(Rcpp::NumericMatrix X) {
   std::cout << X.nrow() << std::endl;
   std::cout << X.ncol() << std::endl;

   std::cout << X(100,4) << std::endl;
}

/*** R
# create a matrix to be passed to the C++ function
mat = matrix(3, nrow=10, ncol=3)
myFn(mat)
*/

# 10
# 3
# 3.96421e+252

几个快速的:

  1. 您的代码包含 RcppArmadillo header 并设置依赖项,但不使用 RcppArmadillo。不好的做法(虽然无害)。

  2. 你使用 std::cout,CRAN 和 WRE 都不赞成。

  3. 如果需要边界控制,请使用 .at(i,j) 访问器;出于性能原因,默认情况下这是关闭的。

下面的修改示例。

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void myFn(Rcpp::NumericMatrix X) {
  Rcout << X.nrow() << " " << X.ncol() << std::endl;
  Rcout << X.at(100,4) << std::endl;
}

/*** R
# create a matrix to be passed to the C++ function
mat = matrix(3, nrow=10, ncol=3)
myFn(mat)
*/

如果你运行你得到你想要的错误:

R> Rcpp::sourceCpp("/tmp/indexExample.cpp")

R> # create a matrix to be passed to the C++ function
R> mat = matrix(3, nrow=10, ncol=3)

R> myFn(mat)
10 3
Error in eval(substitute(expr), envir, enclos) (from srcConn#3) : index out of bounds
R>