为什么我在尝试将数组中的值写入 CSV 文件中时会出现段错误

Why do I get segfault trying to write a value in an array into a CSV file

本文关键字:文件 段错误 错误 CSV 数组 为什么      更新时间:2023-10-16

我正在尝试以二进制或原始文件格式读取 8 位图像,并将每个像素放在 csv 文件中的一行中,并在 x、y、z 的 2 个像素内包含 12 个邻域。我一开始只是尝试将每个像素的值写入

// ----------------------- Create pointer to hold input values for ml
short p[1308*1308*200][13];
ofstream full_stack;
full_stack.open("full_stack.csv");
int index;
// // ----------------------- for loop execution
for( int x = 0; x < 1308; x++ ) {
for( int y = 0; y < 1308; y++ ) {
for( int z = 0; z < 200; z++ ) {
index   = x+1308*y+1308*1308*z;
myData.read(buf, sizeof(buf));
memcpy(&value, buf, sizeof(buf));   
p[index][0] =   value;
}
}
}
for ( int i = 0; i < 1308*1308*200; i++){
for ( int j = 0; j < 13; j++){
full_stack << p[i][j] << endl;
}
}
full_stack.close();
}

正如@Sid_S指出的那样,您正在尝试在堆栈上声明一个 8 GB 的数组。如今,典型机器上典型应用程序中的堆栈约为 1-2 兆字节。您需要使用malloc()new或使用 C++ 集合(如std::vector<short>(动态分配数组。假设您有一个二维数组,您需要执行类似std::vector<std::vector<short>>的操作。