Hope you guys enjoyed the video! Just a quick note: the code that I wrote at 16:47 should really be *a2d[y][x] = 2;* since we want the inner loop to iterate through the actual int array data. Don't forget to drop a comment below if something still confuses you about multidimensional arrays, and have a nice day!
@aleksandarsherbula20816 жыл бұрын
May i recommend you put annotations in the video when you make errors like this?
@joemccane99506 жыл бұрын
Also I see allot of questions about using stack allocated arrays for multidimensional arrays and them being consecutive memory, might want to pin a comment explaining why this is, in general, a bad idea.
@MrCynosure4sure6 жыл бұрын
Thank you for your videos. If I create a 2D array/grid/matrix using STL vector e.g. std::vector a2d , will it suffer from the same performance penalty as the int** a2d?
@srrutik94146 жыл бұрын
t cherno how old r u now??
@END-oc4qu6 жыл бұрын
Hey if I wanted to multiply a 2 dimensional array by a value like 10 that has 3 rows and 4 columns with initial values present in each location, why would I set the "setw(5)" with the 5 argument instead of a (4) argument in this manipulator function.
@TheSmellyMoo5 жыл бұрын
I have been programming for 24 years, and used C++ for 15 of them, I make all my money from making my own programs... But I have actually learnt a few really useful things by going back and checking everything against your videos. Turns out there is always more to learn, and I like your teaching style. Thanks.
@zbyna25672 жыл бұрын
26 years of God so much experience
@hugoyoutube1226 Жыл бұрын
Humility is the best programming and learning skill in general :) I love your comment
@totalspelnerd6 жыл бұрын
Been coding in C++ for 4+ years now, don't really know why I'm watching these videos, but sometimes something new pops up. So even though I knew all of this, it was really nice to see you think about not only the intuitive way of doing something, but also the (most of the time) better way. Most people teaching C++ (or any language really) just looks at one approach, and it's usually the intuitive one not the better one. Really great video! Keep it up!
@alt0v144 жыл бұрын
Same thing, coding in java for 9+ years... And you know, that trick with arrays must work for java too :)
@zvxcvxcz4 жыл бұрын
@@alt0v14 I don't know what the implementation of Java arrays is, they might already be doing it this way underneath, check the class implementation. This is the kind of reason why I think it is important for universities to teach a low level language first (mine does) rather than a higher level one like Python or Java, so that people know these tricks and that it may actually be what their higher level objects are really doing. There is a tradeoff to this method, you aren't jumping around in memory following pointers, but you are doing arithmetic calculations on every index. If you can guarantee memory contiguity with one of the other things he mentioned, then you actually might be better off bouncing through the pointers than doing the calculations.
@CarvellFenton4 жыл бұрын
I'm in a similar situation, but find the extra insight in these videos related to the "why" of doing something very beneficial. That is something that is overlooked in many other training presentations and is really key, I think, to making people better programmers; thinking through why they are writing code in a specific way rather than just copying and pasting something to try and get the job done.
@danibarack5523 жыл бұрын
You should have mentioned the much simpler stack declaration of such arrays: int a[n][n];. Also, if you want it heap allocated and don't want fragmentation, you could do int* a=new int[n*n]; int** m=new int*[n]; for(i=0;i
@acasualviewer5861Ай бұрын
I guess a performance fanatic might argue that m[i][j] is less performant than m[i+j*WIDTH] because of the additional pointer dereferencing.
@Shade_111120 күн бұрын
@@acasualviewer5861 One can add operator overriding (i, j) for direct plane array access, and keep the [i][j] overloading too. Use the former for performance-critical parts, and the latter for general slicing that is not performance critical, but for slightly nicer code clarity when working with large arrays.
@Xxp0r6 жыл бұрын
Love this video. Would love to see an in-depth video of writing a freelist/mempool that also takes into consideration dynamic allocation when the pool is empty and the optimisations around it.
@kanskejonasidag16 жыл бұрын
OOOooh that would be suuper cool!
@doctortrouserpants13872 жыл бұрын
it's 2022 and I'm learning a ton from your various series - i love that you show how simple and easy things can be, as well as demystifying complex stuff - amazing energy - huge thanks and i'll defo be donating to your patreon.
@mpphelps2 жыл бұрын
If anyone is curious about the time difference between allocating/deleting a 3d array versus a 3d flattened array of size 5x5x5. It's significant. Below are my bench mark times using the timing method learned from previous video: 3D ARRAY 0.0278ms 0.0164ms 0.011ms 0.0112ms Average: 0.0166ms 3D ARRAY FLATTENED 0.0015ms 0.0008ms 0.0025ms 0.0009ms Average: 0.001425 Optimization improvement by 11.65 times faster. WOW
@jdsaravaiya6468 Жыл бұрын
i was searching for this. although i think u can have this type of array if you want to manage individual 1d array
@dmitripogosian5084 Жыл бұрын
Well, if you have 1000*1000*1000 array on which you do complex calculations later, allocation time is not that relevant. Saying that, what about addressing ? What is faster, get a value from 1D array (including index calculation) or 3D one ? Let us say, it is random access.
@thewelder3538 Жыл бұрын
Come on, there is NO SUCH THING as a 3D array. Arrays are all flat, memory is just a size.
@gabrielbarrantes6946 Жыл бұрын
@@dmitripogosian5084 since the calculation is a couple of sums and a multiplication, I don't think is even noticeable, most likely is better to have it flattened to have less cache misses
@dmitripogosian5084 Жыл бұрын
@@gabrielbarrantes6946 Well, if the calculation sits in your inner most loop, the difference between one multiplications and two multiplications can be approaching factor of 2 for your program's runtime. But I agree that cache misses are more degrading most of the time
@mzjayne16 жыл бұрын
I just did a search for this topic on your page the other day. I'm so glad to see it up !! I absolutely love your work and it's helped me understand c++ in a way I never thought possible. I'm self teaching so your work means a lot to me !! Thanks
@jadenataylor2 жыл бұрын
12:43 was super helpful. I was having trouble with memory leaks, so thank you so much!
@christianlennertz57806 жыл бұрын
First time I understood arrays in C++. So, I have to say, good teaching! Thank you for that!
@dmytroboiko1 Жыл бұрын
This is super cool, man. Realizing that this whole "matrix" or 2D,3D,ND arrays can be flattened and it WILL BE FASTER is super cool. Love the way you are looking on a code-things, from a different angle i would say. Thanks.
@frisosmit89206 жыл бұрын
I would love to see a video on caching and accessing memory in the right way
@dennisjosesilva Жыл бұрын
Another great video. I once saw another option to have 2d-array and keep the data contiguously stored in memory: const int ncols = 5, nrows = 5; int *array = new int[ncols * nrows]; int **a2d = new int*[nrows]; for (int i = 0; i < nrows; i++) a2d[i] = &array[i * ncols]; for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncols; j++) a2d[i][j] = 5; } The problem is we have to keep in mind that "a2d" and "array" point to the same data and the code to delete the data might be a little bit confusing: delete[] array; delete[] a2d;
@Calebinator19994 жыл бұрын
The vibration at 5:25 had me looking all over for a rogue phone going off in my room.
@christopheracconcia42284 жыл бұрын
Cherno you're a very good teacher. The way you speak and the physical environments that you teach from take the fear away from learning this sort of stuff. Very appreciative of your videos.
@killeraloo32472 жыл бұрын
Thank you for posting this video. Now I am clear about multidimensional array.
@Pablo360able6 ай бұрын
Fascinating. I vaguely remember some of this from when I was first learning C++. I think that C# multidimensional arrays are really single-dimensional arrays under the hood, so they avoid some of the downfalls of actual meta-arrays listed here.
@spamfilter322 жыл бұрын
I have also been watching your series on the Sparky game engine and this explanation on 2d arrays and pseudo 2d arrays made the [ x + y * w ] notation make so much more sense.
@jroberts34254 жыл бұрын
I've not come across the single 1d array method of storing multi d arrays. I'm following along your cpp series and your lectures are amazing. Thanks
@kanskejonasidag16 жыл бұрын
At 0:45 the "C" in the guys surname ALMOST lines up with the "C" logo in his laptop. Makes me think of r/mildlyinfuriating...
@smrtfasizmu61612 жыл бұрын
This was my first thought of how to create multi D arrays in C but I found on the Internet people making arrays like this int matrix[2][3]; Ans then you could write int (*ptr)[3] = matrix; Which is kind of an intuitive syntax because if you want to know what you get when you dereference ptr, just look at this expression without a star sign. Also, when I put a 2D array like this on the stack it gets put continously in the memory. If you write ptr[1][2] you will get an offset of (1 * 3 + 2) * sizeof(int) bytes (1*3 because every array has 3 elements). If this same ptr points at an address 100, ptr[4][2] will be at an address 100 + (4*3+2) * 4 = 100 + 56 = 156. That's the approach that I found on the Internet though, what cherno showed in this video was also natural to me as to how you would store multi D arrays. With, Cherno's approach, ptr would be declared like this int **ptr and taking this same example, ptr[4][2] would be at an address that is stored at an address 100 + 4*(sizeof(void*)) and then add 2*sizeof(int). Which means one more jumping through the memory than with the approach that I have mentioned beforehand.
@smrtfasizmu61612 жыл бұрын
Nobody ever said this to me but when you look at pointers, if you want to see what they are pointing to just remove a star. Double pointer has 2 stars, remove one and you get a pointer. Therefore a double pointer is pointing to a pointer. int (*ptr)[3] is pointing to an array of 3 ints, thus, when you dereference it, you will find 3 integers. Not an address, but an array of 3 integers. This also means that when you walk through memory by writing ptr+1 you will move 3*sizeof(int) bytes. On the other hand, if you have a double pointer, if you write doublePtr+1 you will travel sizeof(void*) bytes in memory.
@matrix9140 Жыл бұрын
your explanation was great I understood everything very well, also I like how you teach everything in depth and that makes it much easier to understand.
@elultimopujilense4 жыл бұрын
That was actually a pretty solid explanantion of the subejct. I didnt got confused at all.
@MrDarkyosh6 жыл бұрын
The timing on this is incredible. I am about to start an assignment on this topic and it couldn't have come at a better time :D
@bhaskart4883 жыл бұрын
The Cherno is best for C++ tutorials.
@rufatmammadov606 жыл бұрын
The best explanation of the arrays with pointers on youtube.
@nkklafuenf37543 жыл бұрын
I’ve been learning C++ for six months. Your videos are just right for me! Thank you ;-)
@alexanderdaum80536 жыл бұрын
When you really need to have a 2d array, you could also create a 1d array first, that stores all the data, then create an array of pointers (the 2d array) that stores pointers to {data, data + width, data + 2*width,...}. Then you have a 2d array, which has all its data in one spot. Its a bit tricky to delete it, because you just have to delete the data array and the pointer array, and not every single array row, but I think this can be dealt with.
@jenny-mg6ts4 жыл бұрын
my brain exploded just because of this one video, im scared to watch another tutorial lmao
@getyournekoshere98242 жыл бұрын
great tip about keeping 2d arrays in 1d. just implemented that same idea in my personal project.
@victorlucki85866 жыл бұрын
As always, great video! Although I'm already familiar with most concepts you teach, I learned it all in other languages (mostly Java and C#), so they're a great way for me to get more familiar with C++ Regarding this particular video, I do feel like using a visual representation could work better for explaining multidimensional arrays - at least that has been my experience when teaching other people. Best of luck and keep up the excellent work!
@VOLTDOGmusic6 жыл бұрын
Love you advanced insights and the optimization considerdations! Down with 2D arrays!
@JoshuaKisb6 жыл бұрын
Yes understood. awesome video
@lukenukem80286 жыл бұрын
MicroGut has no videos!
@Ferocious_Imbecile2 жыл бұрын
Best C++ tutorials ever. Love the in depth explanations.
@yavuzselimcagan52332 жыл бұрын
I learnt C in the university and your c++ explanations and lessons have made C clearer also added me a great c++ knowledge. I will also try to compare these two methods with Timer Struct we created in the last episode :D
@yavuzselimcagan52332 жыл бұрын
there is a 0.002 ms difference for a 50*50 int.
@Ebocraze3 жыл бұрын
Life's nit fair as a C++ programmer. Here we are performing mental acrobatics to ensure that we access and read memory in the most efficient manner and create really efficient speedy software. And these Python. R and Java coders hold themselves out as true programmers. I dare say that we C++ programmers are true blue software engineers and the rest software mechanics ( smile )
@mjrupprecht64582 жыл бұрын
Great video man! Straight to the point with simple examples.
@Anubis110110 ай бұрын
i tried to sidestep the entire pointer confusion issue by using pointer arithmetic, kinda like you did in the latter half. people groan whenever its brought up, but once you get the basic idea down, you can write equations for any situation and just re-use the equations as necessary. much easier than keeping track of what level of pointer abstraction youre on, at least for me. plus it uses contiguous memory, so its fast and easy to work with. the equation i worked out is *(xAxis + xOffset * yAxis + yOffset), where xAxis is the variable name/reference. yAxis will vary based on use case, but this equation can be expanded to n-dimensions as necessary, and it really saved me headaches when making my rpg game in the terminal by using it for the screen buffer (yAxis in that case was the vertical draw size, or in other words the number of rows).
@75hilmar3 жыл бұрын
Hey thanks for that last part about the memory fragmentation. I think I am going to store them in a single array for starters and write a logic to access them.
@chawnneal1593 жыл бұрын
19:21 cherno: the 1d array is much much much faster than the 2d array! me: how much faster? **me grinning because I watched the previous timer class video**
@chawnneal1593 жыл бұрын
ran the 5x5 ex with the Timer class('struct') and got 0.0052ms vs 0.0022ms
@MACAYCZ2 жыл бұрын
Thx:)))))) I was looking for this like whole day, thx a lot:))
@redwolf16524 жыл бұрын
Nice, I will send ink to this video to my teacher called me slacker for avoiding 2d arrays and just using 1d array. Thanx, great video. Got lost a bit inside other videos, watched some of them 4-5 times to understand all you are explaining. Some visualisation except coding would be nice, but cant really ask for that, as this isn't your main job.
@ibrahimtouman22794 жыл бұрын
At 05:10, it is not necessarily true that you have allocated 200 bytes of memory in your second case (i.e., new int*[50]). For example, a single pointer occupies 8 bytes of memory in X86-64 (aka, AMD64) computer architecture, in which case you will need to allocate 400 bytes of memory in your second case (i.e., new int*[50]).
@seankang83185 жыл бұрын
Thank you very much for this video tutorial! I was having such a hard time understanding pointer to pointer multidimensional array, and you explained it so well. Thank you again.
@AxElKo4406 жыл бұрын
Nobody can explain like you. Love this video
@ankitpaudel5 жыл бұрын
This series would be one of the best sellers if it were on Udemy or anywhere else ........hands down best....
@cprn.3 жыл бұрын
18:06 Holy crap, I thought he's gonna make us take a test!
@vertigo69825 жыл бұрын
Seeing that nested for loop reminded me of the Big O Notation.. Do you have a video on that ? If not you should make one.. your fans will thank you.. I still have a hard time remembering, and using it. And the fact I have a hard time remember that also reminds me I have a hard time remembering the Rule of Three as well.. another idea for a video.. but I dont forget RAII lol.. The acronym worked.
@leixun4 жыл бұрын
*My takeaways:* 1. Create a 2D array 2:20 2. Create a 3D array 7:47 3. How to delete 2D array on the heap memory 12:00 4. Multidimensional arrays cause memory fragmentation and are slow 13:15 5. We can improve the speed by converting 2D arrays to 1D arrays 15:54
@venunathan36804 жыл бұрын
Well, there are actually much easier ways of handling multidimensional arrays. For Stack allocation of 10*10 array: int Mat[10][10]; For Heap allocation of 10*10 array: int (*Mat)[10] = new int[10][10]; // Declaring (*Mat)[10] means : Name Mat refers to (a pointer to (an int array of size 10)). // The brackets are needed in the declaration of (*Mat)[10]. The explanation has brackets to remove ambiguity from misinterpreted English. Mat[4][5] = 6; delete [] Mat; This kind of allocation is easy to handle. There is no memory fragmentation and is almost as good as 1D array. This also easily extends to higher dimensions: For Heap allocation of 10*10*10 array: int (*Mat)[10][10] = new int[10][10][10]; Mat[4][5][0] = 6; delete [] Mat; (I'm not too sure of the deletion part. So just verify it before using it for anything important.)
@tobeqz70654 жыл бұрын
My god, this video is a livesaver, thank you so much!
@oscar.90176 жыл бұрын
well done ! I really love your toturials
@wes4436 жыл бұрын
right there with you. excited for more videos regarding performance
@goldenlava10194 жыл бұрын
useful equations for 1D array (17:00) index = y * width + x x = -((y * width) - index) y = (int)index / width
@ianmubangizi67216 жыл бұрын
Cherno Great Videos man, they have really helped me in understanding how memory works - Hahaha I have to say when you teach you're using your pro thinking and not a beginner's mindset which is not a bad thing, because I have no problem with it [I have learnt to code properly in my own way] but a lot of my class mats can't understand you when I shared your video. I Like that you put a lot of emphasis on memory and performance, but my friends don't understand you and so do I sometimes - I have to pause and draw what your saying, it would be great if you could start with a diagram of what your going to do or are doing, never the less great work man I really enjoy your videos I don't know how you manage.
4 жыл бұрын
A lot easier to understand and much more intuitive doing this in Assembly language, where you're dealing with the raw pointers and direct memory structures all the time. C++, on these aspects at least, certainly does over-complicate what is a fairly simple concept. It might be easier to think in terms of pointers to pointer tables, where each pointer in that table points to the start of your array of actual data.
@SeanForeman4 жыл бұрын
Makes perfect sense. I am now very frightened of multi-dimensional array memory leaks. If I wanted this, I would write it once, template it and make sure that template code is correct.
@Recovered4 жыл бұрын
Hi, in the final example if you want to make it slightly more efficient you could pull the 'y*5' to outside the xloop to safe keep calculating it for every element
@char76056 жыл бұрын
Love this series so much!
@gameking0086 жыл бұрын
The second array will actually allocate 400 bytes on a 64-bit architecture. The size of a pointer depends on the architecture.
@hussamq99095 жыл бұрын
Great video, been searching forever for this.
@georgegu3374 Жыл бұрын
good explaination. instead of 50x50, i suggest use asymatrical matrix like 3x5 to explain this would be better for all to understand the dimentions. and further more, compare initializing matrix in stack vs heap.
@shrivastavakartik37876 жыл бұрын
A more like 17:28 way with one 'for' loop :-) something useful 'for' a beginner like me... for(int i=0 ; i
@osere64325 жыл бұрын
That's close but broken code... You've asked it to access element 0, 6, 12, 18, 24, 30, 36... 144 I think what you're looking for is : for(int i = 0; i < 5*5; i++){ Array[ i ] = 2 }
@rastaarmando70584 жыл бұрын
that doesn't work.
@andreashadjigeorgiou15964 жыл бұрын
You could allocate all memory of integers (which is the actual data we need), and also all the pointers to integers, pointers to pointers to integer etc... in advance. And then go and assign all pointers to the right locations so that you can still access data like this array[ ][ ][ ] but the data being contiguous in memory!! ;)
@johnhuelsenbeck35 Жыл бұрын
Nice video. I think accessing elements using the i * width + j is faster than the [I][j] method. If you check the assembly that is produced, the former requires fewer instructions. I now avoid allocating 2D arrays and stick with 1D arrays, overloading (x,y) for access. (I think this must be why the Eigen library uses (x,y) type access to its native matrix class instead of [x][y] access.) When I did allocate 2D arrays, I would do it with only two allocs: int** x = new*[] and then x[0] = new int[nr * nc]. You then set the other pointers from 1...nc-1, so I would still have a 1D array for the data elements.
@danielketcheson19652 жыл бұрын
22 year old Cherno knows what 32 year old me will know. A modern day western sensei. (bow emoji with handshake-like respect behind it)
@KirkDem2 жыл бұрын
I am curious on how you might make a 2darray that a user can specify the size of? I know it would have to be a pointer.
@zch74914 жыл бұрын
Correct me if I am wrong, but this is also why linked list structures are also frowned upon, your next "element" is in some random bit of memory and getting to it will result in a cache miss?
@sanyi_derda4 жыл бұрын
Opinions on using a vector of vectors as multidimensional array? Elements of a vector are stored in a continuous chunk of memory so a vector of vectors is also continuous.
@michaelmahn43736 жыл бұрын
This is all specific to heap allocation, isn't it? If I stack allocate int[5][5] and int[25] are both consecutive memory.
@BurgerKingHarkinian6 жыл бұрын
Yep, seems like what he said only applies to heap allocated multidimensional arrays.
@joemccane99506 жыл бұрын
Yup your both right, stack is always consecutive in the order you allocate that's why using the stack is always faster. However most arrays are heap allocated, especially multidimensional, since they can get very big very fast. So you want to use the heap to avoid stack overflow; of course if they are very small you should be fine on the stack.
@ineednochannelyoutube53845 жыл бұрын
@@nijucow the 50x50x50 array was 125kbytes. Its a good 7% of the stack, bht wont overflow it.
@tonyflow62444 жыл бұрын
I need no channel youtube! As long as you use int this is true. Wouldn’t be difficult to define a data type 15x larger.
@zvxcvxcz4 жыл бұрын
@@nijucow You can request larger stack at program start if you know how big they will need to be. Edit: Not always of course, often the size initially allowed is the maximum, but it could also be smaller in the case of shared clusters.
@LucyAndLily50211 ай бұрын
awesome! 1-dimensional array to store bitmap!
@StefanGliga486 жыл бұрын
AFAIK there are ways to allocate contiguous blocks for heap 2d arrays so they needn't be avoided. And stack allocated 2d arrays are pretty neat.
@田琪-x5r4 жыл бұрын
Cherno,your series that's awesome!!!! Thank you!
@theinquisitor186 жыл бұрын
C++ has actually come quite easy to me. Now we get to multiple dimensions arrays. Well there goes that streak.
@h.hristov6 жыл бұрын
Thanks for the video Cherno. I have a question. Are stack allocated multidimensional arrays lay out contiguously in memory?
@joemccane99506 жыл бұрын
Hristo Hristov yes they are but are, in general, a bad idea because they can be very large in memory and can cause a stack overflow later on in your code due to you using a large portion of the limited stack space available with the array.
@robromijnders Жыл бұрын
I imagine libraries exist to handle multidimensional arrays, lookups and deletes. Do you have any overview and pros/cons of them?
@vinayakkolhapure1506 жыл бұрын
This is my first video on your channel . I liked your video.....explanation is very good. One thing which could have been better is you could have pictorially represented multidimensional array to clear the confusion. Also one more suggestion, please show the code for longer duration, I know you are handsome but still :)
@MakeTechPtyLtd5 жыл бұрын
@17:28 thats cool. Is it fair to say you're a bit more commited to the dimension size with this method? say for example you decide you need another "column" in the inner array once a bunch of data has been created and stored on eeprom or other media.
@swoopertr6 жыл бұрын
You are the best teacher ever :)
@povilaspetrauskas6766 жыл бұрын
Is there a way to use smart pointers for multi-dimensional arrays for memory management? If so, how should you do it, or why not?
@expurple4 жыл бұрын
If the life cycle of your matrix is simple then there's no need really, just create a local std::vector or the same with std::array. Back to your question, sure, there is a way to use a smart pointer instead, if the situation requires it.
@ziyuanlu4577 ай бұрын
thank you for your brilliant video! 👍 I have a question that storing 2-D data in a 1-D array involves one addition, one multiplication, and one addressing, while in a 2-D array it only involves addressing and potential cache missing. Will the later always be slower than the former? Thanks for reading my comment!
@方宇凡-g4d4 жыл бұрын
Shouldn't it be "array of pointers" at 10:53, and "array" at 10:56, so that in 11:01 it is actually an "integer"?
@jojo-fp1zv6 жыл бұрын
But when the for loop reaches the last cycle, x and y are 4. So [ x + y * 5 ] is (4 + 4) * 5 = 40 -> so it must be out of bounds. Or is C calculating like this : 4 + (4 * 5)?
@muhammed_genco4 жыл бұрын
Thanks, I was looking for an explanation like your comment... I was confused at this point of code.
@sandspatel6 жыл бұрын
You mention the deficiency in getting contiguous memory is a performance drag. Then what would you use for multidimensional data organisation? Is a more performance optimal option then to use c++ vectors? How do they compare?
@zvxcvxcz4 жыл бұрын
Vectors actually are guaranteed to get contiguous memory, sort of. Members of the vector will be contiguous and evenly spaced, but you could have gaps due to alignment in the objects that are in your vector. Should be contiguous if you are just putting in something like int, float, or double though and not some bigger object. I guess you need to compare the cost of dereferencing vs. the index arithmetic. It may also depend on your access pattern, you will hear this talked about when it comes to things like linear algebra libraries, BLAS, etc... Mainly whether the library functions are written for row major or column major matrices. My naive guess is that vectors will do better for random access.
@darkfuji1964 жыл бұрын
It depends on what exactly your application is. If you're really interested, look up algorithms for storing matricies, they tend to have interesting block structures that make accessing contiguous memory fast.
@JensN113 Жыл бұрын
Can we build our own class, store the data in a 1-dimensional array and overload the [] operator to still have the grid syntax but without cache misses? Should be possible, or?
@Ponemo104 жыл бұрын
Really great video! Been reading some C++ code recently and I have seen a lot this use of 1D array to represent grids and did not understand why. Now I do! Hahaha Thank you for awesome and enlightening videos Cherno!
@9SMTM65 жыл бұрын
Was waiting for you to get to the fragmentation all along. Isn't there a way to treat it like a contiguous 1-d array but re-add the syntactic sugar of n-d Arrays later? Like some trickery with a union type?
@kirkpennock29973 жыл бұрын
How about a video showing how to store an 2d array of floats? I need to store a vga frame of distance float values. I am getting lost in the array type vs the pointer type not matching and that does not make sense to me.
@neobaud513 Жыл бұрын
Great video. I think if you allocate the array on the stack it will be one continuous block right?
@shishirjais4 жыл бұрын
I love your videos Cherno. You're a great teacher. Just a minor suggestion. In your example of 3D arrays, you could have used x, y, and z as all different sizes (say 50, 40 and 30) so as to make things more clear to beginners. Just my 2 cents though :) And cheers again for these awesome videos which help even an experienced programmer like me. Thank you.
4 жыл бұрын
Excellent and more intuitive suggestion.
@ستيلوأورقة5 жыл бұрын
Thank you, you make c++ much fun.
@rituraj60436 жыл бұрын
How to get input from user to create a dynamic 2d array of n inputs
@shenzi11185 жыл бұрын
Very good video! I am pretty late to the party I guess. My c++ skill is beginner level, just did the c++ introduction free MIT course online. But I read a book about data oriented design and how pointer chasing and memory fragmentation kills performance, so I could guess the conclusion of the video in advance when thinking about the "textbook array of pointer c++ multidimensional array style" and that a single dimensional array does better. A question I have: What should we do now, should we write an array wrapper in all our programs ourselves or is there a template/library that we are expected to use for this?
@VoidAshen3 жыл бұрын
here is a simple explanation if u dont get it say the int* is a column, then int** are rows for each row there are gonna be 50 int* and int*** is height of a cube lets say , so for each unit of height there are gonna be 50 rows or 50 int** which have 50 int* so..get it now?
@jelaszad93234 жыл бұрын
Hello, there is a possibilty to create 2D array and having data in one row, example below: int** AllocMatrix2D(size_t dim1, size_t dim2) { int** matrix2d = new int* [dim1]; int* dumm = new int[dim1 * dim2]; for (size_t i = 0; i < dim1; ++i) matrix2d[i] = dumm + i * dim2; return matrix2d; } void deleteMatrix2D(int**& matrix2d) { delete[] matrix2d[0]; delete[] matrix2d; matrix2d = 0;
@Mateus.0074 жыл бұрын
How about int (*a)[4] = new int(4 * n)? Works using [][] operators.
@jdsaravaiya6468 Жыл бұрын
i dont think it's just 25 ints, Assuming 32bit PTR : 5x5 it would be 25+5(intptrs) = 30 ints (for 2D) and it will be 5x5x5(ints)+5x5(ptr to row)8 +5(ptr to plane) = 125+25+5 = 155 ints. basically for each dimension you pay with more memory X all the previous dimension count. this issue is not present in contiguous multi dim array, at most you might be using MxNxsizeof(member) + 2 x sizeof(index used). assuming you dont use stack to allocate your max index as aswell.
@FreeDomSy-nk9ue4 жыл бұрын
Can't we just use malloc to allocate contiguous memory of size x*y and then initialize our array[x][y] the same way (2 for loops)?? In this case we would have the advantage of the notation [x][y] while eliminating any possible performance issues.
@lampartzjardu77347 ай бұрын
how i shuld do to create a 2d array and add step by step rows ? I mean like vectorname.push_back(1d array) ? Is that possible ?
@saeed_tavakoli3 жыл бұрын
How can I allocate an array partially? For example, I have a matrix with some non-zero elements (e.g., just diagonal), can I reduce the allocation to that essential elements without losing direct indexing? It means somehow I compact used memory without affecting the efficiency?