Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 4
    There's still an extra array of pointers. Code using the array has to do the extra layer of indirection, because it can't assume array2d[i] = buffer + i * sizeX. So this helps to a small degree, but in code using the array, the compiler can't just increment pointers to scan the array. Commented Sep 11, 2015 at 22:56
  • 8
    Yes, this is exactly the way to do it. But it's the C way to do it, in C++ we'd use make_unique<int[]>(sizeX*sizeY) to set up the contiguous storage, and make_unique<int*[]>(sizeX) to set up storage for the pointers (which should be assigned the same way you show). This frees you from the requirement to call delete[] twice at the end.
    – Ben Voigt
    Commented Jan 21, 2017 at 3:08
  • This answer is kind of making a ton of sense to me, even more considering @BenVoigt comment. The extra array of pointers @PeterCordes refer to, is it temp? Considering the benefits (continuos 2d array with unknown dimentions at compile time), I'm not sure I care having it dangling. I didn't understant what @PeterCordes mean by extra layer of indirection, what is it? Why the parenthesis, array2d[i] = (temp + i * sizeX);
    – KcFnMi
    Commented Aug 1, 2018 at 1:44
  • delete[] array2d[0] is the same as delete[] temp?
    – KcFnMi
    Commented Aug 2, 2018 at 12:46
  • This is still not a good solution; you are storing many pointers that can be calculated instead, and element access would need two pointer indirections. Use a proper multidimensional array library, such as Boost.ublas, Boost.MultiArray, or gitlab.com/correaa/boost-multi (disclaimer, my library).
    – alfC
    Commented Dec 17, 2023 at 8:53