Timeline for How do I declare a 2d array in C++ using new?
Current License: CC BY-SA 2.5
15 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Feb 12 at 15:57 | comment | added | Ben Voigt | @Kphysics: for example stackoverflow.com/a/29375830/103167 | |
Feb 12 at 15:56 | comment | added | Ben Voigt |
@Kphysics: I've recommended that exact approach myself several times. Except don't use new , use make_unique<T*[]> and make_unique<T[]>
|
|
Feb 10 at 12:13 | comment | added | Kphysics | @BenVoigt , please take a look at my comment just above: you get contiguous memory, new and delete it in one statement, and get both stiles of referencing: a[i][j] is ok and m[i*colCount+j] also ok. | |
Feb 10 at 12:10 | comment | added | Kphysics | @KevinLoney What I usually do is allocate contiguous memory in one go: int** a = new int*[rowCount]; int* m= new int[rowCount * colCount]; for(int i = 0; i < rowCount; ++i) a[i] = m+i * colCount; | |
Oct 9, 2019 at 11:44 | comment | added | C. Binair |
For future readers being confused about the indexing, i.e. whether it should be i*sizeX+j or i*sizeY+j . Well it depends on how you see the matrix. I hope this makes it clearer: int * ary = new int[nRows*nColumns] and indexing via ary[iRow*nColumns + iColumns]
|
|
Apr 27, 2018 at 6:32 | comment | added | Nahiyan | Yes, it should be i * sizeX + j. I was having a hard time debugging my program until I saw the comment here. | |
May 3, 2017 at 22:13 | comment | added | Dietrich Epp | @Borna: In general using a single 2D array is going to be faster than an array of arrays. Following two pointers can cause pipeline stalls. As always, it depends on access patterns. | |
May 3, 2017 at 21:08 | comment | added | Boy | @DietrichEpp Is the reading from an array faster if we allocate one block only? | |
Nov 2, 2016 at 0:33 | comment | added | Miro Rodozov | hm, nice thinking, indeed it's only a matter of representation - the rest is perspective. clever | |
Oct 4, 2015 at 20:29 | comment | added | arao6 |
Shouldn't it be i*sizeX+j ? If I recall correctly, with row major ordering it should be row*numColumns+col.
|
|
Mar 31, 2015 at 19:43 | comment | added | Ben Voigt | @Kevin: Allocating just a single contiguous block is the way to go (less impact on allocator, better locality, etc). But you don't have to sacrifice clean subscripting. See stackoverflow.com/a/29375830/103167 | |
Dec 13, 2012 at 18:59 | review | Suggested edits | |||
Dec 13, 2012 at 19:11 | |||||
Jun 1, 2009 at 21:48 | history | edited | Kevin Loney | CC BY-SA 2.5 |
added 274 characters in body
|
Jun 1, 2009 at 21:35 | comment | added | Dietrich Epp | It's a little heavier weight than it needs to be, and it allocates more blocks than you need. Multidimensional arrays only need one block of memory, they don't need one block per row. Allocating only one block makes cleanup simpler too. | |
Jun 1, 2009 at 20:46 | history | answered | Kevin Loney | CC BY-SA 2.5 |