【发布时间】:2021-12-28 14:45:50
【问题描述】:
我正在使用 C++ 构建一个数组,然后将其传递给 Python(类似于:Embed python / numpy in C++)。我是 C++ 新手,我对代码的一些细节感到困惑。我希望我能理解这段代码是如何工作的,因为我需要改变它。所以我的问题是:这个初始化数组的方法是什么?
const int SIZE{ 10 };
double(*c_arr)[SIZE]{ new double[SIZE][SIZE] };
为了记录,我已经能够通过调用将它变成一个矩形数组:
const int numberRows = 5000;
const int numberColumns = 500;
double(*c_arr)[numberColumns]{ new double[numberRows][numberColumns] };
我填充数组:
// fill the array from a file
std::string line;
int row = 0;
int column = 0;
while (std::getline(dataFile, line)) {
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, '\t')) {
c_arr[row][column] = std::stod(cell);
column++;
}
row++;
column = 0;
if (row == numberRows) {
break;
}
}
我还是不明白double(*c_arr) 是什么意思。每当我尝试以不同方式初始化此数组时,都会出现错误。例如:double *c_arr[numberRows][numberColumns]; 在我尝试填充数组 c_arr[row][column] = std::stod(cell); 时引发错误。如果我将初始化更改为:double c_arr[numberRows][numberColumns];,那么运行时会出现分段错误。我最终想要实现的是一个返回指向数组的指针的函数;类似:
double *load_data(int rows, int columns) {
double(*c_arr)[columns]{ new double[rows][columns] };
//fill array here
return (c_arr)
}
当我构造这样一个函数时,在columns 变量第二次出现时出现错误:expression must have a constant value -- the value of parameter "columns" cannot be used as a constant。我真的不知道该怎么做,但我希望如果我能理解数组初始化,我将能够正确构造load_data 函数。
【问题讨论】:
-
指向数组的指针 (
int (*p)[5]) 与指针数组 (int *p[5]) 不同。我认为这是你困惑的根源。 -
啊,这样就更有意义了。那么,指针周围的括号意味着指针指向对象吗?像这样……?
-
这是变量的声明语法。在复杂的情况下,它是出了名的棘手,因为我们在名称 (
p) 之前写了一些东西,在之后写了一些东西,而且顺序并不容易理解。在某些情况下需要括号来强制需要的类型,就像我上面做的例子一样。int (*p)[5]表示 p 是指向 5 个整数数组的指针。int *p[5]被解析为int *(p[5]),这是一个由 5 个指向 int 的指针组成的数组。