Timeline for How do I declare a 2d array in C++ using new?
Current License: CC BY-SA 4.0
7 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Dec 17, 2023 at 8:53 | comment | added | alfC | 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). | |
Aug 2, 2018 at 12:46 | comment | added | KcFnMi | delete[] array2d[0] is the same as delete[] temp? | |
Aug 1, 2018 at 12:19 | history | edited | Levi Morrison | CC BY-SA 4.0 |
Light grammar fix
|
Aug 1, 2018 at 1:44 | comment | added | KcFnMi |
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) ;
|
|
Jan 21, 2017 at 3:08 | comment | added | Ben Voigt |
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.
|
|
Sep 11, 2015 at 22:56 | comment | added | Peter Cordes |
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.
|
|
Dec 28, 2014 at 1:01 | history | answered | kamshi | CC BY-SA 3.0 |