-1

The following code is supposed to write a 2D array (quad_array) to a binary file. The code creates the file (quads.dat) but does not write anything to it (0 bytes).

XMFLOAT3 * quad_array;
quad_array = new XMFLOAT3 * [quad_width];
for (unsigned int x = 0; x < quad_width; x++) {
    quad_array[x] = new XMFLOAT3[quad_height];
}
// ... fills quad_array with data...
ofstream ofs("quads.dat", std::ofstream::binary);
ofs.open("quads.dat");
streamsize size = sizeof(XMFLOAT3)*quad_height*quad_width;
ofs.write((char*)&quad_array[0][0], size);
ofs.close();
r m
  • 177
  • 13
  • 1
    I don't see any 2D arrays in this code. –  Dec 22 '13 at 18:21
  • There is no need to be snarky, it's a pointer based 2D array. Pointing out it is not contiguous in memory would have been useful. – r m Dec 22 '13 at 18:41
  • I am not being snarky, this is not a 2D array. There's no such thing as a "pointer based 2D array"; what you have is a pointer-to-pointer. Searching for similar question (there are dozens of duplicates of this one on SO!) would have been useful. –  Dec 22 '13 at 18:44
  • You are clearly caught up in semantics. I suppose "2D array of pointers" is the most precise. – r m Dec 22 '13 at 18:56
  • No, I'm not confused. The most precise is what I wrote: pointer to pointer (to `XMLFLOAT3`). A 2D array of pointers looks like this: `T *arr[width][height];` –  Dec 22 '13 at 18:58
  • This has nothing to do with confusion, i said semantics. – r m Dec 22 '13 at 18:59

1 Answers1

1

I think that you should remove the

  ofs.open("quads.dat");

statement, because you already gave the filename at the previous line (constructor).

But that is not enough. You don't have a 2D array, but an array of pointers to arrays, so they are not contiguous in memory.

If quad_height and  quad_width are compile-time constants, you could use nested std::array with C++11.

See also this.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    If I ever design a native/systems programming language, the very first thing I will leave out from the C(++) feature list is implicit conversion between arrays and pointers. –  Dec 22 '13 at 18:22
  • Thank you, the open command was preventing the writing. Quad_height and quad_width are not compile-time constants. Even if a pointer based 2D array is not wholly contiguous in memory, quad_array[0][0] to quad_array[0][quad_height] is contiguous correct? So, ofs.write((char*)&quad_array[0][0], size); should be writing one of the columns (plus some gibberish)? – r m Dec 22 '13 at 18:33