Reading file into 2D char array error.

I have a file that contains several records of the same size, all in order. I am able to read in the data into a single char array multiple times, but cannot seem to read it into a 2D array. In the below example, there are 1000 sets of 1000 character data.

I'm using Code::Blocks and mingw.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  // This code works.
  std::ifstream file("sample.dat", std::ios::binary);

  char data[1000];
  int data_size = int(sizeof(data));
  for (int i = 0; i < 1000; i++)
  {
    file.read(data, data_size);
    // Print the data in the loop.
  }


  // This code doesn't work.
  // Process terminated with status -1073741571
  // I read the error was a divide by zero error.

  std::ifstream file("sample.dat", std::ios::binary);

  char data[1000][1000];
  int data_size = int(sizeof(data[0]));
  for (int i = 0; i < 1000; i++)
    file.read(data[i], data_size);
  // All data in matrix, so print as needed.
Last edited on
At line 19 you're creating a megabyte of data on the stack. That's a lot of data. Try making that static instead: static char data[1000][1000];
At line 20, i isn't defined. And you should use size_t. So make this size_t data_size = sizeof(data[0]);
Thanks, that fixed the problem! I forgot about overloading the stack like that.
Registered users can post here. Sign in or register to post.