0

I am having troubles with I/O to file with 2 dimensional dynamic array. It compiles good but it does not work as I want. Example, I save "map" of numbers 1 and after this I change number in source code to example 5 and compile it, now I load my "map" of numbers 1 but when it writes in cycle for at the end it, the output is 5 not 1. Please can somebody help to fix the code?

#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;
}
4

2 回答 2

1

The main problem is this: Hereby

array = new int*[20];

you allocate an array of pointers, and this will not become a two dimensional array as you later do:

array[y] = new int[30];

Note that there is a difference between this

// array of pointers to integer arrays
int ** array = new int*[20];
for(int y=0;y<20;y++)
  array[y] = new int[30];

and this

// two dimensional integer array
int array[20][30];

You cannot assume that your array of arrays will lie in contiguous memory.


Besides: Hereby

out.write((char*)&array, sizeof(array));

you just write out the pointer, not the actual data. Try to print the sizeof(array):

#include <iostream>

int main() {
  int * array = new int[10];
  std::cout << sizeof(array) << std::endl; // probably prints 4 or 8
  return 0;
}

Conclusion: Unless you need to implement this for educational purposes, std::vector will far more conveniently serve you memory management for free. Also have a look on Boost Serialization. It provides functionality for serialization of STL collections.

于 2012-05-22T08:48:34.713 回答
0

The error is in the fact that sizeof(array) equals to the size of a pointer, not the size of dynamically allocated memory. As an effect, you read/write only 4 (or 8) bytes. Use actual array size (in this case 20*30) instead of sizeof(array).

于 2012-05-22T08:41:12.710 回答