Arrays in C++

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey little guys my name is the Cherno and welcome back to my sequel club series I'm back home in Melbourne now so no more crazy hotel rooms or anything minutes to go to call this studio and today when we told me about a raid in super Club so before we start talking about a raise it's really important that you understand what pointers are I'm an entire video based on pointers there will be a card on the screen or a link in the description below definitely check that out first before this video point is a pretty much debate for salaried working typify so you definitely need to understand that so first of all what is an array and array exactly a collection or element it's a bunch of things in a particular order in our case and tablecloth and arranged basically a way to represent a collection of variables is basically a bunch of variables usually at the same time in a row the reason is it's so important and so useful it's because there are countless times where we want to be able to represent a whole collection of data a whole bunch of data and it just doesn't make sense for us to create a whole bunch of variables that really should be grouped together in one data set because variables need to be created manually we need to actually go into the code and specify variables and give them name whereas sometimes we just want to be able to store say 50 integers that represent some sort of data we don't want to have to specify like integer number one is number two and so on all the way to 50 because that first of all is just like that's just terrible because that that's just that's completely unfeasible and unmaintainable imagine having to set all the variable to zero you literally have to write 50 lines of code that you set all of your characters zero manually really really hard to deal with a lot of variables so what we want to do in that case is just use an array to contain all those 50 elements or the same type in this case integers to make our life much much easier so just remember an arrange is basically like having multiple variables in one variable we give an array a single name and through that we can refer to as many variables as we create a be arrayed with let's let me do some code and take a look so defining an array is quite simple suppose that I wanted an array of five integers I would simply write any type that I want the array of I would then give it a name for example example and then in square brackets I put how many I want so we'll just say five and that's it I now have an array of five integers I've basically allocated enough to store five integers now in order to actually set and access those integers I can write the name of the array and then inside square brackets something called an index and an index is wish variable inside that array I'm actually referring to which element I'm referring to so this is the first one we're going to write a zero because it raised in several spots start with zero in some languages such as Lua they start with one which is very very weird and kind of uncommon usually array start with zero meaning that 0 is the first element and we can set this like like a look any other integer because it is just an integer now whilst there is an array of integers when we access one of those elements add a specific index we get the underlying type of the array which is just an integer we can set it equal to 2 for example now you can probably notice here that we allocated space to 5 integers however the first index is 0 which would mean that since we all get aspects of 5 integers the last index is actually 4 not 5 because index number 5 would actually be the sixth element let's set this to something like 4 I'm going to leave the other ones unset now reading these is equally as simple if we wanted to print one we will just specify which index who wanted to print like this if we just specify the actual array and it's just going to print the memory address of it because this is actually a pointer type and as I mentioned when you index an element inside the array you get back the underlying data type so in this case an integer so I kind of course create a new variable and then copy the value from the array back into that variable you can see that the data type here is just a normal integer if I try and access an index that is not inside the array for example I trying to access example at negative 1 or example at 5,000 call something called a memory access violation because I'm trying to access memory that doesn't belong to me now in debug mode you will actually get an error method in a crashed explain to help you debug those problems however in release mode you probably want which means that you've just written into memory that isn't yours now it's really important that you actually be careful with this and make sure that you're always writing inside the bounds of the array because if you're not it can cause problems that can be fairly difficult to debug because you've just modified memory that wasn't part arrey however might be part of another variable neil source code so you've just literally gone out and changed some other variable in your code to something else without realizing it so just make sure that you set up safety checks where needed to make sure that you're not writing up out of the balance we'll talk more about this specific problem and stuff like that in the future now arrays are really well with for loops because full of our indexable loops that go through a particular range right so if we wanted to set every single value inside our example array a full Earth is a really good way of achieving this without a for loop we would have to go through all of these indices and actually accept them manually and that's how we would achieve setting everything dessous however by creating a for loop that goes through the entire length of our array which is five and simply accepts example at I equal to two what we've done is we've looped through the entire array meaning we've gone through index 0 to index 4 since index 4 is the last pointer which eyes less than 5 we could have also written less than or equal to 4 however so no one really write code like this and also it'll be a bit of a performance here because they are doing a less than and equal comparison so it has to do that equals comparison instead of just a less than comparison so it's almost always written and less than 5 instead of less than or equal to 4 if we run this code now for a breakpoint on our C and get we can take a look at what this actually looks like in our memory so I'm going to go up to this memory view here if you want to know more about that I made a video on debugging and pipa plus again a link a description and a condom screen to that but everything I'm just going to go to the memory address of my array so example is actually a memory address on time because example is an integer pointer so I'm going to type in an example over here and you can see that what I've got here is my twos in a row so one of the really important thing about arrays is that they store their data contiguously which means they saw that I in a row so I've allocated space for five integers meaning I'm literally going to get one integer after the other in memory each integer is 4 bytes so what I've got here is 20 bytes worth of memory in a row which is divided into kind of four byte segments not really divided into four pipe segments however when we access it through our code and all that it is for all intents and purposes divided into four byte segments even though there's no literal division so that's what you see over here in this memory of you you see five 2's which take up four bytes each because they are integers now when we access a specific index by writing example I what it actually does is a text an offset to this memory so if I write example at index 2 it's going to start at the beginning of the array which you can see is this memory address here and it's going to simply add on eight bytes because each integer is 4 bytes we want to access element number two which is its third element since indexing starts at 0 so element number 2 will be 2 times the size of each element so 2 times 4 in our case which bumps up a fight forward to this integer over here so if we write a value to example at index 2 it will write that portion of memory now as I mentioned an array is really just a pointer it's an integer pointer in this case to that block of memory which contains our 5 integers which means that I can actually create a variable here which is just an integer pointer and give it the value of example and you can see that works fine and that will compile just fine because example is just an integer pointer now as I pointed out accessing element number 2 and setting it equal to 5 or something like that will result in us basically writing to an offset of 8 bytes from pointer so this code over here can actually be rewritten using simple pointer arithmetic to actually be pointer plus 2 because we're accessing two elements forward then be referencing this and then setting it equal to something like 6 for example let's move our for loop up before this and give this a shot and see what we get I'll put a breakpoint right over here so if I go to example which is a memory address of our array you can see that element number 2 the third element is set to 5 and then of course it should be set to second steps let's head up done as you can see over here that it was changed to six now I did say eight bytes however you can see that I wrote off true for this pointer the reason I did that is because when you're dealing with pointer arithmetic so basically what I'm just adding values like - - a pointer the number of bytes that is actually going to add it's going to depend on the type so in this case since the pointer is an integer pointer is going to add two times four because four is the size of each integer if I wanted to actually deal with by it either cast this pointer to a data type that is just one by large for example at char and then if I do that I'll have to add on the eight bytes that I talked about since I then want to write in an integer which is 4 bytes not just a single child which is one byte once I actually do the plot 8 I would need to cast this back into an integer pointer and then of course the reference that to get my internship so that I can set it equal to 6 now this is a pretty wild line of code but let's check it out when I hit our 5 go to my example you can see it's set to 5 when I hit f10 you can see we get the exact same result is a set of 6 so yes you can get pretty fancy with this but essentially what I wrote here is exactly what this indexing does it's not magic that's how arrays work they're just a contiguous block of data and you can you can literally in-depth them like their word book and write to a specific page in this case a specific integer no I'm going to wrap this up here pretty soon because I don't want to get too in-depth into arrays and confuse you however you can also create arrays on the Cape we haven't talked about the staff or the sheet mulch or how memory really works much I definitely am going to get to that very very soon Oh for now similarly to how we can create classes by using the new keyboard we can also create arrays by using the new keyword so we'll make another array here I'll call this one another this will be an int pointer and then I'll set it equal to a new instance where decide that I want so let's go with 5 again this code is identical to this code however the lifetime of difference and this is created on the stack it will get destroyed when we reach the end curly bracket and we get out of this scope however it is since it's created on the heap will actually be alive until we destroy it or into our program and so you need to actually delete it using the delete keyword and if this is an array and we allocated using the array operator here so we use the new keyword with the square brackets we need to delete it using the square brackets like this as well let's go ahead and bring back that for loop for our example we'll set it equal to two and I'll do the exact same thing for our other array that's another equal to two of course I could have a friend this in a single for loop but let's head up five so if I type an example over here in my view I get my five two is in a row and of course the pie type in another I'm also going to get the exact same result so why would you allocate dynamically using the nuclear web rather than just creating it on the stack the biggest example is to do with lifetimes right because like anything be allocate with new it will be around until you delete it but we have a function returning and you will reign for example you have to allocate using a nuclear word unless you toss in mount a memory address by the parameter or something like that if you want to actually return an array that's brand-new already it was created inside the function you need to use the new keyword another thing to think about though is memory indirection basically what I mean by that is since we're actually holding a pointer that point is going to point to another block of memory which holds our actual array which results in kind of memory fragmentation and cache misses and all this complex stuff till they're definitely gonna talk about in future video however I'll show you a quick example so that you know what I mean if I create a class over here called entity and I move my example array over here I'll also create a constructor which basically just is my for loop that initializes all this to two and I'll make everything here in public if I create my entity objects like this I'll get rid of all this other code and hit f5 if I go to the memory address of my entity and hit enter you can see that I've got all my memory right there the memory address of entity actually just in line contains all of my twos all of my daughters however if I go back here and I push this over here to be credit on the heat by using a new keyword I'll run that exact same code you can see that if I go to the memory address of my entity I don't see my twos there at all I see this other memory address which of course is this pointer now I can copy this and put it here I'll have to reverse it because at the end Ian nest though this will actually be 0 0-7 d5e and hit enter I get taken to my actual data so there's an indirection again what we've actually got the memory address of a week and another memory address to where our actual array is which means that when we want to access this web basically jumping all around our code first to get to the entity then to get to the array all that stuff so of course whenever possible you want to create your array on the stack to avoid that because jumping around memory like that is definitely a performance hit now there's one more thing I want to mention I know this is a huge video if you guys like these kind of massive video then you have time to watch them but I want to mention arrays instead of both 11 instead of 11 we've got something called standard array which is an actual inbuilt data structure is built into the 11 library a lot of people really like using it over the raw array that I've shown you here because it offers a number of advantages namely being that it includes bounds checking and it actually keeps track of the size of our array one more thing that I didn't mention is that there's actually no way to work out the size of our array if we allocate an array on the heap like this we've set fire to be 5 and in many other languages we can actually write something like example dot size you can't do that in people but there's no way for you to actually know the size of an array now I say no way obviously there is some way because when you delete this array the compiler needs to know how much memory to actually free so yes there is a way to know about its compiler dependent it's possibly sometimes stored at a negative index inside the erase like index negative one it depends on a lot of things and it's very very contrasted basically so you should never be accessing decide an array in the array memory itself that's dangerous if you allocate an array on the stack so if I write in a and in science you can find out what it so it's actually insecured of course it's allocated on the stack which means because the stack pointer contains the offset basically so if you're right sides of and what you'll actually get is the size of the array and by so in this case we have an integer which is 4 bytes we have 5 of them so we have 25 this will give you 20 bytes so if you want to know how many elements are in there you and by the size of the data type which is in so this code will actually give you the account in terms of elements I like to refer this accounts not size personally when I deal with with the word size I'm talking about bytes and one idea would count we're talking about number of elements so this will give you five which is the number of elements that we've allocated however if you try the same thing with this example instead then what you're actually going to get here is the size of an integer pointer which is four wide and then you're going to divide it by five which will give you 4/5 or since this is an integer it will give you zero or nonzero plane which is wrong anyway so you can only use this trick with stack out at arrays if you had to change this to be exact out at array like third it would also work that would also be fine however you really can't trust it and of course as soon as you decide to pass this into a function or anything it becomes an endpoint err and then you're just screwed so what you have to do instead is actually just maintain that sign by yourself I know kind of stuck in that sense but it's just that's just how a pop-up works you have to maintain it yourself the way that I would write this code personally is I would declare a constant size to be five and then I would put this in here now I love it this gives us an arrow because you can't actually do that when you allocate an array on the stack it has to be a compile-time known constant half true with an asterisk because there's a simple slot and there are ways around this which we'll talk about in a later video however this has to be known at compile time so you have to basically market a static you can also use a constant expression here constant expressions of cyclases have to be static anyway as you can see another story for another video this videos going to have so many turn offs because we're really going into the juicy stuff now hope you guys are excited about that so we'll just make it static and we don't really need this a big heart expression so that's really how you deal with this and that in this case telecoil is something like example size because it's dealing with the example array specifically and then you can plug this into all of your for loops and all that stuff to actually notice either your array that's just what you're going to do if you use at people have got 11 standard array here on how to offer you guys how to do that you can just write FTD array we'll make sure to include this as well just Inc which array will give it a name for example another and we basically have to give it a type and account if we're now you'll bracket here it says we need the type name and the size so we'll write int as the type comma 5 as the size and that's it with credit this array and to fill it up of course we can actually do another dot size and there we go we have 5 so it's an easier way to deal with this of course that does have the overhead because it does all of the balance checking if you wanted to and also it actually maintains a size integer as well which you might not want so there is a bit of overhead usually it's worth it so consider using this we'll have a whole video on how that actually works and all that drop in when we finally reached our two structures and start talking about them but just something to think about personally I use raw arrays all time most people probably do a little bit faster and I personally don't really run into many problems with them but again if you're being super safe and you were probably coming from another language you probably do want to use standard array I'm being completely honest it's a lot safer to use standard array than raw arrays however I like to live dangerously anyway I hope you guys enjoyed this video if you did you can show me by hitting that like button and if you really want to pull up this series and see more great episodes like this then you can go to patreon.com/scishow know you'll get access to a whole bunch of rewards for showing your support there and it really does help me produce these videos I'll see you guys next time goodbye [Music] you [Music]
Info
Channel: undefined
Views: 172,685
Rating: 4.9574246 out of 5
Keywords: thecherno, thechernoproject, cherno, c++, programming, gamedev, game development, learn c++, c++ tutorial
Id: ENDaJi08jCU
Channel Id: undefined
Length: 18min 31sec (1111 seconds)
Published: Sat Aug 19 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.