Fixed and Variable Length Arrays in C and C++

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody today we're talking about arrays a few different ways to create them and how those different ways affect the programs that we write and the options that you have as a programmer hey welcome back everybody i haven't really done a beginner video in a while and it seems like in my classes with my students i've been dealing a lot with array issues and so i thought it might be a good day to discuss arrays static arrays dynamic arrays fixed sizes variable sizes pointers to arrays basically all that good stuff both in c n and c plus plus now this is a beginner video but you intermediate programmers may find something that you don't know or you may find something that you have forgotten or not thought about for a while and it's always good to get a refresher now of course there will be code in this video as always source code is available through patreon a big thanks to all of you that support this channel so if you're watching this video you've probably at least heard about a raise maybe it's something that came up in class maybe you're actually coming to this video with a specific question about arrays if by some chance i don't answer it please drop me a question down in the comments below and i will try to get to it in a future video and of course if i do answer your question or you find this video useful please consider dropping the video a like now onto arrays now basically arrays are what we use anytime we want to store a series a bunch of elements these elements can be ints or characters or floats or structs but we want a bunch of them laid out sequentially in memory basically just a list you know 5 10 15 whatever and in c and c plus the elements of our arrays need to be the same type now you can of course use pointer tricks and polymorphism if we're talking about c plus plus to store different kinds of elements in a single array that's not what i'm talking about today but make sure and mention in the comments if you'd like to see a video about that in the future but either way from your compiler's point of view an array is homogeneous meaning that all of the different things in the array are of the same type and if we jump into the code i have a very simple program here we can define our simplest of arrays like this so this array is called a it's gonna have five elements and we can initialize it with the numbers between one and five okay super simple array with an initializer i don't need the initializer this part i could just leave off if i wanted to so this declares a static array of ins and its length is five hey future jacob here i just wanted to jump in and clarify one little thing i realized after i filmed it that i was using the word static and that may get confused with the static keyword in c now i have a video that talks about the static keyword in c i'll link to that in the description please check it out if you're confused but when i say static here what i mean simply is that these arrays don't grow they're a fixed size array the compiler allocates memory for them statically and that memory doesn't grow or shrink it just stays the same that's what i mean by static okay that's it let's get back to the video so this declares a static array of ins and its length is five when the compiler sees this it's going to set aside space in memory for five integers five ins and then we can simply interact with those ins something like this like i can say the first element is the zeroth element so i can do something like this if i want to set that first element to 76 it's important to note for beginners that we do start with zero if you're wondering about why that is i do have a video that talks about that i'll put a link in the description but so here we can set our first element to be 76 and we can also get the value of the second element so something like we could say x equals a square bracket 1. so this is basically going to grab the second element of the array a and assign its value to x and of course what happens when we want to pass our array to a function okay so let's say i've got this array and i want to pass it to a function let's start out with a really simple function let's just say we want to make one that prints out arrays so let's it's not going to return anything for now but we'll call it print array and we're going to pass in an array call it my array and we're going to make its length five okay so just like my array down below so when you pass this in now all i'm going to do is have a quick little for loop we're going to go to five and then each time through the loop we're going to print out the value of the ith element in the array forgot a comma add our semicolon and then down here at the end just to make things look nice let's just add a new line at the end okay so what this is going to do is it's just going to go through and it's going to print out each element in the array on a line and then it's going to end the line once we finish okay nothing too complicated here now if we come down here and we call it on one of our arrays just like this unless just for interest sake let's go down and make a second array that's going to be the same but with some different values and we'll do the reverse of the numbers now we can come in here and we can call it on a and we can call it on b okay so now i'm going to compile my code and come down and i can compile it and we do have one warning which is this x is never used so for now i'm just going to remove these two lines okay now i'm going to compile my code using a little make file that i created nothing fancy here if you are new to make files and you haven't seen these before be sure to check out my other videos on make i'll put links in the description but so using this make file i can come down here and i can compile my program no problem and i can run it and you can see it prints out the elements of each array i'm kind of not liking having a new line at the end of each i meant it to be all on the same line sorry about that so we can recompile and we can run and they are still a little bunched together so let's add a comma and a space make things make our output a little bit cleaner okay here we go so now you can see it prints out the elements in the array all in a line and then it jumps to the next one for the next array so this worked and it's a good first step but it has some limitations i want to talk about them before we move on the first one is that all of this code so far is very very static what i mean by that is that it's fairly inflexible this the length of this array is five this array is five my print array up here can only accept things that are of length five and in reality sometimes we want to deal with different lengths and sometimes we don't necessarily know what the length needs to be until we get into our program and so this limits us a little bit it's not super flexible now one other thing that i would always do in any real program even for static arrays is i would get rid of these magic number fives i would come up here and either pound to find a constant or use a const and let's use constant for now and we'll call this array length set it equal to five and then what we can do here is come down and we'll just replace everything in our program with array length and this basically just gives me the flexibility of saying let's say at some point i want to actually change what the length of all of these different arrays are i can just change it in one place rather than having to remember everywhere in my code that needs to be changed but again let's come back to this question of what if i don't know what length my array needs to be or what if i need arrays to be of different sizes and maybe i want to use a function that can work on all of them so well let's focus on one thing at a time how would i make an array where i can pick the size at runtime now for this i want to show you just a few different options now the classic way to do this is with a pointer so the way i would do this is say so i would specify an integer pointer and then i would call malloc and tell it the size so malik allocates a block of memory and i'm going to tell it the size of the thing i need which is i need the size of an int so that's going to tell me the size and memory of an integer times the size of the thing that i want so in this case i could use array length but i can use really anything in here so i could use seven i can use 567 whatever i want i can basically specify the size i want and this is something that happens at runtime so it's super easy for me to specify the size if i want to make it bigger or smaller say for example i'm going to read in some data and i need to make an array that's the size of the data well that's hard to know beforehand what that's going to look like but with this approach super easy if i have some variable that has that value in it i can just pass it directly there okay so this gives us the ability to create an array of variable size now we can come down here and we can try to print out that array at this point i just want to mention that yes this is a pointer but from now on we can basically just use p like we did any other array and that's because pointers and arrays are almost exactly the same thing look if you're a little fuzzy about the relationship between arrays and pointers i do have another video that looks at that issue another beginner video i actually mentioned it before already but there is a link down in the description so please check it out if this is a little fuzzy now before i go into printing this out the other thing that we need to do differently about this array is once we're done with it we also need to free that pointer so once we're done with that array once we don't need it anymore then we're basically going to release it and say hey i don't need this pointer anymore so i'm giving it back to the system to the allocator to the heap okay so now let's revisit our print array function so i i can call it just like this and that's cool except when i go around to run it you're gonna notice that well something happens first of all i said i wanted it to be 567 entries but i only got five right i'm able to pass it in but my program up here basically just says i only work on arrays of length 5. so we want to make this function a little more flexible i would like to be able to actually print out arrays of any length and so what you're going to see instead is you're going to see a pattern with a lot of functions that take arrays as arguments is instead they're going to pass in a pointer and they're not going to specify this length right here they're going to pass in two arguments instead you're going to get an array and you're going to get a length argument okay and then right here we basically would come down here change this length in our loop so now we're going to go basically to the length that gets passed in and the rest of this just stays the same right we just now are saying instead of me knowing beforehand that everything that's going to come in is going to be length 5. now i'm going to ask you to give me the length you the programmer the person calling this function tells me how long this thing is and then i will just respect that okay so then down here when we call it we would need to pass in the lengths let's use our integer array length and then down here okay so i don't have i'm still using a magic number here but for now that's fine let's make it a little bit shorter so it'll still fit on one line but so we have 15 15 okay great now if i come down here i can run it and you can see okay it works fine on my first two and then it works fine also on my p array and one thing to keep in mind here is that yes all of these entries right now are zeros but that's not guaranteed to be the case when you get memory from malik you're not guaranteed to have zeros you can use calc which actually is guaranteed to zero them out or you can also go through and make sure you initialize this data to something else so you could have another for loop in here that actually goes through and initializes your variables so like for example we could do this go up to 15. i really need to pound to find that somewhere but i'm not going to just for the moment so let's have this one count up too so we're just initializing this to a certain value and mostly i'm doing this so you can see that the values change so now you can see that yes we went from 0 to 14 instead of just all zeros but like i said before if you don't initialize it you're not guaranteed that they're all going to start out as zeros so if you want them to all be zero you could either start out with a for loop that sets them all to zero or you could use something like memset to set them all to zero any of those approaches will work just fine now one thing that i want to point out here with this printarray function is that we're basically trusting the caller to give us the right length if the caller sends us the wrong length for whatever reason then i could handle either too few entries or worse i can read or write too many entries which can corrupt memory or just access memory that we aren't supposed to access which could give us garbage results or it could seg fault like for example let's just say i come down here array length and i say i give it a length that is twice as long so it's going to be 10. and if we run this i don't really know what we're going to get but you can see that we ended up with a bunch of just garbage numbers right we basically just were reading whatever memory happens to be right next to a and it doesn't happen to be anything helpful and so we got the length wrong this just messed us up and so when you're using this approach you do have to be very careful to get the lengths right now if you're coming from a higher level language like java python ruby or even c plus plus if you've been mostly using vectors you might be wondering why can't i just programmatically get the length of this thing why isn't there some get length method or i mean we're talking about c here so why isn't there a get length function that you just pass in an array and it just grabs the length and the thing is is that c and c plus plus arrays don't store a length with the array in memory they set aside memory the compiler is going to set aside memory for the array but there is no length stored in there so you really just have to keep track of that length yourself okay now speaking of c plus plus let's just make a quick copy of this program let's make a c plus version of this okay and this just allows us to talk about one other option and of course you will note that in my makefile i already set this up so that it will actually compile c and cpp files using the c plus plus compiler for the one and the c compiler for the other no problem but i just need to add array to two in here so now it will compile both versions oops i forgot to name it right so let's arraytest.cpp we're going to move it to arraytest2.cpp let's clear this okay now we should be able to compile it and of course okay so one thing you are noticing here is that c plus plus has a few different requirements they're a little picky about what's coming back from malik and so they would want me to cast it in c plus to basically say this is an in pointer no problem okay but so we have our programs they're both working our c plus plus version and our c version the reason i wanted to show you this is simply that most c plus plus programmers would not allocate it like this using malloc although you absolutely can it's no problem but instead we can also replace this with the new operator like this so this might be a little prettier this is basically just saying give me a new integer array that has 15 elements no problem so that's going to function exactly the same except that down here instead of free now we need to say delete p okay so we're basically just taking advantage of these operators and because we're deleting an array we need our square brackets here and now if we compile it okay so we can compile this no problem and we can run it and everything's working the same okay now i've had people ask in the past whether or not you can use free instead of delete to release a block of memory that was allocated with new and in practice this is really going to depend on how new and delete are implemented if delete was just translated by the compiler into a free call then sure this could work why not but that's not guaranteed to be the case c plus plus could actually be doing something differently with new than with malik and so you really shouldn't do that so when your programs use free with pointers that came from malik use delete with pointers that came from new okay now what do we do if we want to resize an array this is a question that comes up a lot and for this let's jump back into our c example let's look at this array that we got from malik if we are in c we can really simply change the size of this so i can just say p equals re alec i pass in the same pointer that i got from malik so that's going to basically say this is i want to reallocate this block and i give it the new size that i want so in this case i still want integers but maybe i want 20 of them so i'm basically saying give me five more than i had originally and so this is going to reallocate the block so now if i come in here we're going to have a length of 20. now keep in mind that again those were not initialized and so when i run this so in this case it's printing them all out in this case we're seeing that they're all zeros but let's say that i had if we go back and we see and we initialize them to an actual value the initial ones and we recompile then you notice that basically the only ones that are initialized are these first 15. the last five that i just added on here they're just zeros and again you're not guaranteed that they're going to be zeros they could be anything they just happen to be zeros in this case and so of course you can see that this works in your programs you might want to see about initializing those new entries anytime you realize something just before you get too far into things but now if we jump back into our c plus version what about resizing our array over here well this is one situation where new and delete are kind of a pain i can't exactly just say resize this array i could allocate a bigger array and copy my data over from my smaller array and then delete the old array and that's just a pain and i know that this is essentially what realic may be doing under the hood but the point is is i didn't have to do it and so that's always a plus so in this case what's a c programmer to do will they stoop down to the old c style interface maybe but most often what they're going to do is just use vectors or some other container class from the standard template library that handles resizing for them and of course that's fine too small amount of overhead but probably nothing to worry about of course let me know in the comments if you'd like to see a video on vectors containers or other c plus topics but let's not get derailed because there's more to say about arrays so back in the old days statically defined arrays like this had to have a constant size so basically 5 works 7 works 15 works but some dynamic variable x doesn't work at least that's how it used to be later versions of the c standard library allowed array sizes to be any integer expression so for example say i wanted to make an array that would store the lengths of the different arguments passed into my program so basically i want one integer for every element of my arg v array then i can do something like this here i can just make an integer array we'll call it arg lengths and we're going to make it the length arc c right because that's what argc tells us rxe is this integer coming in and so we're saying i want an array and i want it to be the size of arc c whatever rxc happens to be and then i can go through let's just copy this and go to argc and then what i can do is something like let's just get the length since that's what i said i was going to be getting and we'll say arg lengths i is string length arg vi okay so what this is going to do is it's going to go through and get the string length of each of my arguments and it's going to store them in my array so now down here we can use print array on my arg lengths array pass in rxc and so this way back in the old days would not have worked oh and it still doesn't work today because i forgot to include string dot h but now if we run this like this well you can see okay right off the bat uh there's only one argument and it is length eleven okay it turns out that that's array test if i pass in a bunch of other arguments and i run it you can see that sure enough we have one of length 11 we've got a bunch that are length three and so this array is not it's still not very dynamic in the sense that it's not changing size while my program is running it's never resized but my code is more flexible now and this can make a lot of your programs a little simpler in the old days for something like this you would have to call malek so we would have to specify the size so we would have to specify the size of the int and the number of elements and all of that and that's not really a big deal either way but you have options and in some cases that might be the better option and so i hope this video helps you keep things straight so i hope that helps be sure to check out my other videos on c and other low-level programming concepts subscribe to the channel if you don't want to miss out on the next one and i'll see you then
Info
Channel: Jacob Sorber
Views: 15,591
Rating: 4.9445982 out of 5
Keywords: variable length arrays in c, variable lenght arrays in c, variable length arrays, fixed arrays, how to declare arrays, arrays in c, arrays in c++, c arrays, data structures, malloc, free, calloc, realloc, new, delete, square brackets, programming tutorial, variable arrays in c, variable arrays in c++, jacob sorber, c language, c++ language, dynamic arrays, static arrays
Id: rww_OHQOmbs
Channel Id: undefined
Length: 20min 24sec (1224 seconds)
Published: Tue Nov 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.