我在使用 2 维动态数组进行归档时遇到了 I/O 问题。它编译得很好,但不能按我的意愿工作。例如,我保存数字 1 的“ map ”,然后我将源代码中的数字更改为示例 5 并编译它,现在我加载我的数字 1 的“ map ”,但是当它在循环中写到最后时,输出是 5 不是 1。有人可以帮助修复代码吗?
#include <iostream>
#include <fstream>
int main()
{
int ** array;
array = new int*[20];
for(int y=0;y<20;y++)
array[y] = new int[30];
for(int y=0;y < 20;y++)
for(int x=0;x < 30;x++)
array[y][x] = 1;
int volba = 1;
std::cin >> volba;
if(volba)
{
std::ifstream in("map",std::ios::in | std::ios::binary);
if(!in.is_open())
std::cout << "in map open error\n";
in.read((char*)&array, sizeof(array));
in.close();
std::cout << "loaded\n";
}
else
{
std::ofstream out("map",std::ios::out | std::ios::binary);
if(!out.is_open())
std::cout << "out map open error\n";
out.write((char*)&array, sizeof(array));
out.close();
std::cout << "saved\n";
}
std::cout << "array\n";
for(int y=0;y < 20;y++)
{
for(int x=0;x < 30;x++)
std::cout << array[y][x] << " ";
std::cout << std::endl;
}
for(int y=0;y<20;y++)
delete [] array[y];
delete [] array;
return 0;
}
最佳答案
主要问题是这样的:特此
array = new int*[20];
你分配了一个指针数组,这不会像你以后做的那样变成一个二维数组:
array[y] = new int[30];
注意这两者是有区别的
// array of pointers to integer arrays
int ** array = new int*[20];
for(int y=0;y<20;y++)
array[y] = new int[30];
还有这个
// two dimensional integer array
int array[20][30];
您不能假设您的数组数组将位于连续的内存中。
此外: 特此
out.write((char*)&array, sizeof(array));
你只是写出了指针,而不是实际的数据。尝试打印 sizeof(array)
:
#include <iostream>
int main() {
int * array = new int[10];
std::cout << sizeof(array) << std::endl; // probably prints 4 or 8
return 0;
}
结论:除非您出于教育目的需要实现此功能,std::vector将更方便地免费为您提供内存管理服务。也可以看看 Boost Serialization .它提供了 STL 集合的序列化功能。
关于c++ - 二进制 I/O 到具有二维动态数组的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698495/