我想用 CSV 中的值填充一個雙指標二維陣列。我不想在填充之前讀取 csv 檔案來獲取陣列的大小,我想用指標而不是 std::vector 來做。我當前的代碼是這個
std::pair<int, int> readFile(const std::string &filename, int **matrix) {
std::fstream file{filename, std::ios::in};
if (file.is_open()) {
std::string line{};
int col{0};
int row{0};
while (std::getline(file, line)) {
// Check how many cols there are
int len = std::count(begin(line), end(line), ',') 1;
// Allocate a vector with size the cols found before
int *tmp = reinterpret_cast<int *>(calloc(len, sizeof(int)));
col = 0;
// Fill the temp vector with the read numbers
while (line.size() > 0) {
int num{-1};
// This is just to parse a number, nothing special here
if (line.find(",") != std::string::npos) {
num = std::stoi(line.substr(0, line.find(",")));
line.erase(0, line.find(",") 1); // 1 to also delete delimiter
} else {
num = std::stoi(line);
line = ""; // Set line empty to go out of the while
}
tmp[col] = num;
col ;
}
// Assign the temporal vector to a row of the matrix
matrix[row] = tmp;
row ;
}
return {row, col};
}
std::cout << "Failed to open file at " << filename << std::endl;
return {-1, -1};
}
int main() {
int **matrix;
auto shape = readFile("file.csv", matrix);
for (size_t row = 0; row < shape.first; row ) {
for (size_t col = 0; col < shape.second; col ) {
std::cout << matrix[row][col] << " ";
}
std::cout << std::endl;
}
// Free the pointers
for (size_t row = 0; row < shape.first; row ) {
free(matrix[row]);
}
}
我目前的結果是:
0 0 -751362032 21853 1
2 3 4 2 3
2 1 3 4 5
3 2 1 4 3
2 2 2 2 2
free(): double free detected in tcache 2
Aborted (core dumped)
似乎第一個 tmp 向量在列印之前被釋放(其余值是正確的)。知道我錯過了什么嗎?
uj5u.com熱心網友回復:
您將傳遞matrix給readFile未初始化的函式,然后繼續使用matrix[i]=tmp. 這可能會導致各種問題,因為您正在使用不屬于您的記憶體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419834.html
標籤:
