我得到错误:EXPRESSION 必须有一个常数值。有没有一种方法可以实际使用变量,因为我的行可能会随着要读取的每个文件而改变。
Image readFile(string fileName) {
ifstream file;
file.open(fileName);
int row;
int column;
Image image(0, 0);
if(file.is_open()){
file >> row;
file >> column;
}
int **row[row]; // error right here!!!!!!!!!!!!!!!!!!!!!!!!! ERROR:EXPRESSION MUST HAVE A CONSTANT VALUE
file.close();
image(row, column);
return image(row, column);
最佳答案
如果我可以给你一条建议:在这种情况下不要使用原始内存。坚持使用 RAII 并为 2d 数据使用容器。
std::vector<std::vector<int>> data;
如果您在某种程度上担心性能,请查看此答案,了解为什么要改用连续存储:Why is dynamic 2 dimensional data storage (pointer-to-pointer or vector-of-vector) "bad" for simple 2d storage .
手动原始内存处理很可能导致内存泄漏、未定义行为等错误。
关于C++创建指针时如何使用变量作为指针的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17639838/