CS50 Data Structures Overview
Transcript
[MUSIC PLAYING]
DAVID J. MALAN: All right, this is CS50. And this is week 5. And among our goals for today are to revisit some topics from past weeks but to focus all the more on design possibilities, particularly by way of data structures. So data structures, again, is this way via which you can structure your data. But more specifically in C, It's how you can use your computer's memory in interesting and, daresay, clever ways to actually solve problems more effectively. But we're going to see today that there's actually different types of data structures. And we'll make the distinction between abstractions, like high-level descriptions of these structures and the lower-level implementation details so to speak. So in particular, we'll talk first today about what we call abstract data types. So an abstract data type is like a data structure. But it offers certain properties, certain characteristics. And it's actually up to the programmer how
to implement the underlying implementation details. So, for instance, there's actually this abstract data type that's common in computing known as a queue. And from the real world, most of us are presumably familiar with queues, otherwise known in the US typically as lines or forming lines. In fact, I have here three bags of cookies. Could I get three volunteers to come up on stage and queue up? OK, I saw your hand first. How about your hand second? And in the blue. OK, come on down, just you three. Come on over. And if you want to queue up over here if you could.
Come on down. Thank you. As we begin, do you want to introduce yourselves first? NAFTALI HOROWITZ: Hi. My name is Naftali Horowitz. I'm a first year studying computer science and economics. And I sleep at Hurlbut Hall. DAVID J. MALAN: All right, next. CATHERINE: Hi, everyone, my name is Catherine. I'm planning on studying engineering. I'm not sure mechanical or electrical yet but one of the two. And I'm currently in Kennedy. DAVID J. MALAN: Nice. Nice to meet. ISABELLA: Hi, everyone. I'm Isabella. I'm in Strauss. And I plan on majoring in computer science. DAVID J. MALAN: Wonderful. Well, welcome to all three of you. And I think this will be pretty straightforward. I have here these three bags of cookies. You formed nicely this line or this queue. So if you'd like to come up first and take your cookies, thank you. And right that way, that's all there is to this demonstration. Your cookies as well. Right this way. And your cookies. Right this way. Wonderfully well done.
Thank you to our volunteers. The point is actually sincere, though, simple as that demonstration was. And as easy as it was to get those cookies, queues actually manifest a property that actually is germane to a lot of problem solving and computing and the real world. Specifically, queues offer this characteristic, FIFO, first in first out. And indeed as our volunteers just noticed, as they queued up on stage, 1, 2, 3, that is the order in which I handed them their cookies. And daresay it's a very equitable approach. It's very fair. First come, first served might be a more casual way of describing FIFO, first in, first out. Now, structures like these actually offer specific operations that make sense. And in the context of queues, we generally describe these operations as enqueueing and dequeueing So when our first three volunteers came up, they enqueued. And as I handed them each a bag of cookies, they dequeued and exited in that same order.
Now, how could you go about implementing a queue in code, specifically in C? Well, we can actually implement it in bunches of different ways. But perhaps the most obvious is to borrow our old friend, namely arrays. And we could use a data structure that looks a little something like this, whereby we specify the total capacity of this data structure. For instance, we might store a total of 50 people or just 3 in this case. We might define our structure then as containing those people as simply an array. And if a person is a data type that we've defined in week past, you could imagine each of our volunteers is indeed a person. And we've stored them one after the other contiguously in memory by way of this actual array. But we do need to keep track inside of a queue using one other piece of data-- namely, we need to keep track of an integer, like the size, like how many people are actually in the queue at this moment. Because if we have a total capacity of 50,
I'd like to if I only have three volunteers. Then I can do some quick arithmetic and know that I could have fit another 47 people in this same queue. But it's finite. Of course, if we had 50 volunteers all wanting cookies, that's as many people as we could actually handle. So there is this upper bound then on how many we could fit. But there's yet other ways for storing data inside of a computer's memory. And there's this other abstract data type known as a stack. And stacks are actually omnipresent as well even though it's not necessarily the system you would want when you line up on stage. For instance, could we get three more volunteers? OK, I saw a hand here, right here, and right here. Come on down. We'll have the orchestra come up this time. All right, come on over. And if you wouldn't mind, come on over. We'll do introductions first. This will be almost as easy as the last one if you want to introduce yourself.
And let me just stack you against the lectern this time. So if you could go there. And if you could come over here. And if you could come over here, we'll stack all three of you. So you were first. So you're first in the stack. SPEAKER: Hi. I'm [INAUDIBLE]. I have no idea what I'm studying. And I live in Strauss. DAVID J. MALAN: Wonderful. And next? SPEAKER: Hi. I'm [? Tanai. ?] I'm studying econ and CS. And I live in Canada. CLARA: Hi. I'm Clara. I want to study applied math. And I'm in Wigglesworth. DAVID J. MALAN: Wonderful. Welcome, to all three of you. And if I may, let me just advance a bit more information about stacks. The catch is that stacks actually support what's known as LIFO, so last in, first out, which is sort of the opposite really of a queue or a line. So in fact you were last in line. So here we have your cookies. Thank you so much. And if you'd like to exit that way, we have your cookies here. Thank you so much. We'd you to exit this way.
And even though you were first, LIFO doesn't really give you any cookies because you're first in, not last in. So, yeah, OK, point's made. We'll give you the cookies. All right, so thank you to all three of our volunteers. But LIFO, suffice to say, doesn't offer the same fairness guarantees as a queue or a line more traditionally. And imagine just lining up in any store or the dining hall or the like. Ideally, you want the people running the place to adhere to that queue, to that line so that FIFO is preserved if you indeed care about being first, whereas there are contexts in which LIFO does actually make sense. In fact, if you think about Gmail, your inbox, or Outlook, typically you're viewing your inbox as a stack right. Because when you get new mail, where does it end up? It actually ends up in the top. And if you're like me, odds are which emails do you tend to first? I mean, probably the ones on the top, the ones that
came in last, most recently that is and that might actually be to the detriment of people who emailed you earlier today or yesterday. Because once they sort of fall off the bottom of your screen, frankly, unless you click next, you may never see those emails again. But stacks are indeed one way of storing data. And Google and Microsoft presumably made the judgment call that, in general, we users want to see the most recent data first. The last information might be the first we want out. Now, just in terms of nomenclature, the two operations that are analogous to enqueueing and dequeueing but with this property of LIFO are instead called push and pop. So when our first volunteer came up on stage, so to speak, I pushed him onto the stack against the lectern there. Second person was pushed. Third person was pushed. And then when it was time to hand out the cookies, we popped them, so to speak, one after the other but preserving that LIFO property.
But here's where things are a little interesting in terms of implementation details. A stack could be implemented almost identically underneath the hood to a queue because what do you need? You need an array of people, which we could use our person data type for past classes. We have to keep track of how many people are in the stack so that even if we have a capacity of like 50, we know at least that we can store 3 plus maybe 47 others. Now, there's still going to be a change in the underlying implementation details because not pictured here is the actual C code that actually pushes and pops or enqueues and dequeues. So whatever loops you're using, whatever code you're using, odds are that's where those properties are going to be implemented. FIFO versus LIFO, you're going to implement maybe the loop in this direction instead of this one or some such distinction. But at the end of the day, stacks and queues
are just abstract data types in the sense that we can implement them in bunches of ways, two of them among them here thus far on the screen. But that array is going to come back to bite us. Because if you only have a capacity of 50, what happens if 51 people want cookies next time? You just don't have room for them even though, clearly, we have enough room for the people themselves. We have enough memory. So it seems a little shortsighted to limit just how much data can fit in our data structures. So with that said, a friend of ours, Shannon Duvall at Elon University, kindly put together a visualization of the same. And allow me to introduce you to two fellows known as Jack and Lou. If we could dim the lights for this video. [VIDEO PLAYBACK] [MUSIC PLAYING]
- Once upon a time, there was a guy named Jack. When it came to making friends, Jack did not have the knack. So Jack went to talk to the most popular guy he knew. He went up to Lou and asked what do I do? Lou saw that his friend was really distressed. Well, Lou began, just look how you're dressed. Don't you have any clothes with a different look? Yes, said Jack. I sure do. Come to my house and I'll show them to you. So they went off to Jack's. And Jack showed Lou the box where he kept all his shirts and his pants and his socks. Lou said, I see you have all your clothes in a pile. Why don't you wear some others once in a while? Jack said, well, when I remove clothes and socks, I wash them and put them away in the box. Then comes the next morning, and up I hop. I go to the box and get my clothes off the top. Lou quickly realized the problem with Jack. He kept clothes, CDs, and books in a stack.
When he reached for something to read or to wear, he chose the top book or underwear. Then when he was done, he would put it right back. Back it would go on top of the stack. I know the solution, said the triumphant Lou. You need to learn to start using a queue. Lou took Jack's clothes and hung them in a closet. And when he had emptied the box, he just tossed it. Then he said now, Jack, at the end of the day, put your clothes on the left when you put them away. Then tomorrow morning when you see the sun shine, get your clothes from the right from the end of the line. Don't you see, said Lou? It will be so nice. You'll wear everything once before you wear something twice. And with everything in queues in his closet and shelf, Jack started to feel quite sure of himself all thanks to Lou and his wonderful queue.
[END PLAYBACK] DAVID J. MALAN: So the same-- wonderful, thanks to Shannon-- so you might have noticed I wear black all the time so we could make a similar gag about here's what my stack of clothes at home looks. Even though I might own a blue and a red sweatshirt, it doesn't really work if you're popping everything from a stack every time, cleaning it, replenishing the blacks sweaters before the red or the blue even get popped themselves. But we're going to focus today not just on stacks and queues which for us are really meant to motivate different ways of designing data even though the implementation details might differ. But we're going to start focusing on solving some problems that invariably we'd be bumping up against anyway as we develop more and more real world software, not just smaller programs as in class. And arrays, recall, are what? What's the key characteristic or definition
of an array with respect to your computer's memory and storing things in it? Yeah? AUDIENCE: It stores the data contiguously. DAVID J. MALAN: Perfect. So it stores the data contiguously back to back to back. And as we've seen thus far, when you allocate space for an array, you typically do it with square brackets. You specify a number in those brackets or maybe a constant, like capacity, like I just did. And that fixates just how much data you can actually store in there. We did see last week, though, that we could start to use malloc to allocate an equivalent number of bytes. But even that, when you call it just once, gives you back a specific finite number of bytes. So you're similarly deciding in advance how much memory you can store in an array. So let's consider what kinds of problems this could get us into. So here's an array of size three. And suppose for the sake of discussion we've already put three numbers into it 1, 2, and 3 literally.
Suppose now we want to add a fourth number to that array. Well, where does it go? Intuitively and pictorially, you'd like to think it could go there. But remember the context we introduced last week when we talked about computers' memories. There's lots of stuff going on. And if you only ask the computer, the operating system, room for three integers, who knows what's here and here and here, not to mention everywhere else on the screen? So if we zoom out for instance, we might like to put the number four there. But we can't if in that greater context there's a lot more stuff going on. So for instance, suppose that elsewhere in my same program or function I've already created a string like H-E-L-L-O, comma, space, world, backslash 0. Just by bad luck, that could be allocated right next to my 1, 2, 3. Why? Well, if I ask the operating system for space for three numbers, then I ask the operating system for space for a string,
it's pretty reasonable for the computer to put those things back to back, because it's not going to anticipate for us that, well, maybe they actually want four numbers eventually or five numbers or more. Now, as for all of these Oscars the Grouch, that's just meant to represent pictorially here the notion of garbage values. There's clearly other bytes there and available. I don't know what it is. And I don't care what it is. But I do care that I can't just presume to put something right where I want in the computer's memory unless I preemptively ask it for more memory. Now, if all of those are garbage values, which is to say that who cares what they are-- it's just junk left over from previous runs of the function or the like-- there's clearly plenty of room for a fourth number. I could put the number four here or here or here or down here or here or here. But why would I not want to just plop the four wherever there is a garbage value currently? Yeah?
AUDIENCE: Because you want it to be next to your array of 1, 2, 3. DAVID J. MALAN: Exactly, I want it to be next to my array of 1, 2, 3 because, again, arrays must be and must remain contiguous. Now, that's not a deal breaker because where else could I put maybe the entire array? Well, there's room up here for four numbers. There's room down here for four numbers. So that's fine. And that could be a solution to the problem. If you've run out of space in your fixed size array, well maybe I just abstract everything else away, and I just move my array to a different location that's a little bit bigger. But there is going to be a downside. Even though this is a solution, even though I can certainly copy the 1, the 2, the 3-- and now I can plop the 4 there. And, heck, I can then let go of the old memory in some way and give it back to the operating system to be reused later. This is successful. But why intuitively might we not want this to be our solution of creating a new array that's a little bigger, copying the old into the new, and getting rid of the old?
Good, yeah, I think I had one more step. Suppose I want to add a fifth number, a sixth number. That's a lot of work. And, in fact, what's the expensive part or what's the slow part of that story? Yeah? AUDIENCE: It takes a lot of time. DAVID J. MALAN: It takes a lot of time. But specifically, what's taking time if we can put our finger on it? Yeah, in the back? AUDIENCE: You're using twice as much. DAVID J. MALAN: OK, for a period of time, I'm using twice as much memory, which certainly seems wasteful because even though I don't eventually need it, it is going to mushroom and then shrink back down, which seems like an inefficient use of resources. But what specifically is slow about this process too? Yeah, in the middle. AUDIENCE: You're iterating through the original array to copy it over. DAVID J. MALAN: Yeah, good choice of words. You're iterating over the array to copy it over using a for loop, a while loop.
So it's probably like big O of n steps just to copy the array and technically big O of n plus 1 if we had one more. But that's still big O of n. So it's the copying, the moving of the data, so to speak, that's certainly correct. But maybe it's not the best design. Wouldn't it be better if we could do something otherwise? Well, let's consider what this might actually translate into in code and what the implications then might be. Let me switch over here to VS Code. Let me propose to open up a file called list.c brand new. And let's create this list of numbers and then add to it over time and see when and where we actually bump up against these problems. So let me include standard io.h in order to simply be able to print things out ultimately, int main void, so no need for command line arguments here. Let me give myself an array called list just of size 3 for consistency with the picture thus far. And now let me go ahead and just manually
make it look like in memory what it did on the screen. So list bracket 0 is going to equal to number 1. List bracket 1 is going to equal the number 2. And list bracket 2 equals number three. So even though the array is, of course, zero indexed, I'm using more familiar 1, 2, 3 as my digits here. Now, suppose I want to print these things out. Let's just do something as a simple exercise. So for int i equals 0, i is less than 3 i plus plus. Inside of this loop, I'm going to do something simple like print out iteratively, as you note, backslash n list bracket i. So very simple program. It's not the best design because I've got this magic number there. I'm hard coding the 3. But the point is just to go through the motions of demonstrating how this code works. Good, you got it in before I hit compile. So wait. Thank you. All right. Maybe round of applause. Thank you. [APPLAUSE] All right.
All right, so this is going to get aggressive, though, eventually. So let me add the semicolon. Let me recompile this list. Seems to compile OK. And if I do ./list, I should see, of course, 1, 2, 3. So the code works. There's no memory constraints here because I'm not trying to actually add some values. But let me consider how I could go about implementing this idea of copying everything from the old array to the new array, frankly, just to see how annoying it is, how painful it is. So you're about to see the code escalate quickly. And it will be helpful to try to wrap your mind around each individual step even though if you take a step back, it's going to look like a crazy amount of code to solve a simple idea. But that's the point. We're going to get to a place, particularly in week 6 where all of what we're about to do reduces to one line of code. So hang in there for now. So let me go ahead and do this.
If I want to create a version of this code that can grow to fit more numbers, for instance, how can I go about doing this or at least demonstrate as much? Well, I cannot use an array in this traditional way of using square brackets because that makes list, the variable, forever of size 3. I can't free it. Remember free you can only use with malloc. So you can't give it back and then recreate it using this syntax. But I can use this trick from last time, whereby, if I know there is this function called malloc, whose purpose in life is to give me memory, I could, for instance re-declare list to be a pointer so to speak that is the address of a chunk of memory. And I could ask malloc for a chunk of memory namely of size 3 but not 3 per se, three integers for good measure. So technically that's three times the size of whatever an int is. Now, for our purposes today, that's technically 3 times 4 or 12.
But I'm trying to do this very generally in case we use it on an old computer or maybe a future computer, where the size of an int might very well change. That's why I'm using size of int. It will tell me always the correct answer for my computer. So to use malloc-- not going to catch me on this one-- what header file do I need to add? Standard? AUDIENCE: Standard lib.h. DAVID J. MALAN: Standard lib.h. So I'm going to go ahead and include standard lib.h, which gives me access to malloc. And what I'm going to additionally do is practice what I preach last week, whereby in extreme cases malloc can return not the address of an actual chunk of memory. What else can malloc return in cases of error? Yeah? AUDIENCE: Null. DAVID J. MALAN: Null, N-U-L-L in all caps, which represents technically address 0. But you're never supposed to use address 0. So it's a special sentinel value that just means something went wrong. Do not proceed. So it's going to add some bulk to my code.
But it is good practice. So if list at this point actually equals equals null, there's no more work to be done here. I've got to abort the demo altogether. So I'm going to return 1 just arbitrarily to say we're done with this exercise. It's not going to be germane for class. We can surely find room for three integers but best practice whenever using malloc. Now, this code here does not need to change because list is now still a chunk of memory of size 12, I can actually get away with still using square bracket notation and treating this chunk of memory as though it's an array. And this is a bit subtle. But recall from last time, we talked briefly about pointer arithmetic, whereby the computer can do some arithmetic, some addition, subtraction on the actual addresses to get from one location to the other. And that's what the computer is going to do here. Because it says list bracket 0, that's essentially just going to put the number 1 literally at the beginning
of that chunk of memory. And because this is a modern computer, it's going to take four bytes in total. But I don't want to put the number 4 here to shift it over myself. Because I'm using square brackets and because the computer knows that this chunk of memory is being treated as a chunk of addresses of integers, pointer arithmetic magically kicks in. So what the computer is going to do for me is put this 1 at location 0. It's going to put this number 2 at location 1 times size of int, so 4.
And it's going to put this number 3 at location 2 times size of int, which gives me 8. So in other words, you don't have to think about how big that chunk of memory is if you already gave the compiler a clue as to the size. For our purposes today, don't worry too much about that. The bigger takeaway is that when you allocate space using malloc, you can certainly treat it as though it's an array using week 2 notation, which is arguably simpler than using dots and stars and all of that. But this isn't quite enough now because let me stipulate that for the sake of discussion, at this point in time here on line 16, where the cursor is blinking, suppose I realize just for the sake of discussion, oh, I should have allocated space for four integers instead of three. Now, obviously, if I were writing this for real, I should just go fix the code now and recompile it altogether? But let's just pretend for the sake of discussion
that somewhere in your program you want to dynamically allocate more space and free up the old in order to implement this idea of copying from old to new memory. So how could I do that? Well, let me go ahead and temporarily give myself another chunk of memory. And I'm going to literally call it tmp for short, which is a common convention, tmp. I'm going to set that equal to the amount of space that I actually do now want. So I'm to say four times the size of an int. So technically it'll give me 16 but space for four integers this time. And what that's doing for me in code is essentially trying to find me space for four integers elsewhere that might very well be garbage values now. But I can, therefore, reuse them. So once I've done this, something could still go wrong. And I could check if temp equals equals null, then actually I should exit altogether and finish up. But there's a subtlety here. And you don't need to dwell too much on this for today.
But there is technically a bug right now. Why based on week 4, last week, might it not be correct technically to immediately return 1 and abort the program altogether at this point? AUDIENCE: I think when you allocate memory sometimes it has garbage values. DAVID J. MALAN: OK, so when you allocate memory, sometimes there might be garbage values there that is true. But that is to say that those 16 bytes might be garbage values, have Oscar the grouch's all on the screen. But tmp itself will literally be the return value of malloc. And malloc will always return to you the address of a valid chunk of memory. Or it will return null. So this line is actually OK. What I don't love is that I'm returning 1 immediately. AUDIENCE: I think [INAUDIBLE]. DAVID J. MALAN: Yes, so this is where it's subtle. It's not quite right to just abort right now and return 1. Why? Because up here, remember, a few moments ago we used malloc presumably successfully.
Because if we got all the way down here, we did not abort on line 9. So we kept going. But that means we've allocated three times size event, so 12 bytes earlier. So frankly, if you compile this code, run it, and then ask Valgrind, it's going to identify a memory leak of size 12 because, as you know, we did not free the original memory. So this is where frankly C does get a little annoying because you and I as the programmers have to remember all of these details. So what I really want to do here, before I return 1, to be best practice, I want to free the original list. So I give back those bytes to the operating system. Now, as an aside, technically when any program quits, all of the memory is going to be given back to the operating system. But practicing what I'm preaching now will get you into better situations later. Because if you don't free up memory, you will have leaks. And that's when our own Macs and PCs tend
to start to slow down and use up more memory than they should. But let's avoid discussion of more error checking there. Let's just assume that now I'm on line 23 of this program, whereby I have presumably successfully allocated enough space. So the next step after allocating these four bytes is to, as you noted earlier, iteratively copy the old numbers into the new space. So this is actually pretty straightforward. I'm going to go ahead. And for int i gets 0, i is less than 3 i plus plus just like I was printing last time. I'm going to go ahead and set the i-th location of temp equal to the i-th location of list, semicolon. And that's it. I'm just copying into the temporary array whatever was in the old array. But that still leaves me with this fourth byte, of course-- or, sorry, this fourth location, where I want to put the number 4. But if I'm going to do that for the sake of discussion even though this isn't really a compelling real world program,
I'm going to just manually go into the last location in tmp, a.k.a. tmp bracket 3 and set that equal to my fourth number. So that's all. The whole point here is to mimic in code what it was we wanted to do here. But now there's one more step. What was the next step after copying the 1, the 2, the 3, and adding the 4? What do I want to do? Now, I can safely free the list. Now I want to go ahead and get rid of the original memory or at least hand it back to the operating system. So here is where I can free the list, not in the case of an error but actually deliberately free the original list because I don't need those 12 bytes anymore. But now if I want to really have quote, unquote list point at this new chunk of memory, well, then I could also do this, list equals temp. So this is a little weird. But recall that list has just now been freed. So even though list technically contains the address of a chunk of memory, it's no longer valid because, again, it was freed.
So, yes, it's still technically there. But it's effectively garbage values now. So I'm certainly free-- no pun intended. I'm certainly allowed to update the value of list. And I want list to now point to the new chunk of memory. So sort of metaphorically, if list was originally pointing at a chunk of memory there, maybe now I want it to point over here. So I'm just updating the value of list ultimately. All right, now that I've got this all done, I think I can just use this same loop as before. I could change the 3 to a 4 because I now have four numbers. At the very bottom of this program though, also subtle, I should probably now at the very end free this list. And for good measure, let me go ahead and return 0. But now I think I have a complete program that, again, to be clear is not how you would write this in the real world because you would not allocate three integers then decide you want to allocate four then fix all of this. But we could probably borrow, copy and paste
some of this code into production code eventually, whereby this would solve some actual problems dynamically. So let me cross my fingers, make list. So far so good, ./list. And I should see 1, 2, 3, 4. So long story short, it's a lot of work just to get from the original array to the second. So ideally, we would not do any of this in the first place. Ideally, what could we do instead? Well, maybe we should just allocate more memory from the get go in order to avoid this problem altogether.
So how might I do that? Well, instead of having allocated an array of size 3, let alone an array of size 4, why don't I just proactively from the beginning of my program allocate an array of size 30 or heck 300 or 3,000 and then just keep track of how much of it I'm using? That would be correct. It would solve the problem of not painting yourself into a corner so quickly. But what remains as an issue? AUDIENCE: You're using a lot of memory. DAVID J. MALAN: I'm using a bunch more memory. Especially if this program's only going to ever manage a few numbers, why are you wasting 100 times more memory than you might actually? And there's an another corner case that could still arise even though this solves the problem. AUDIENCE: If you add another list, you'll run out of memory. DAVID J. MALAN: Exactly, we can eventually still run into the exact same problem because if I want to put 301 numbers in the list or 3,001, well, I'm still going to have to jump through all of these hoops
and reallocate all of that space. And, honestly, now per year concern about the looping, iterating 300 times 3,000 times is certainly eventually going to start to add up if we're doing it a lot in terms of speed and slowdown. So maybe there's a better way altogether than doing this. And indeed there is if we start to treat our computer's memory as a canvas that we can start to use to design data structures more generally. Arrays are a data structure, arguably. They're super simple. They're contiguous chunks of memory. But we could use memory a little more cleverly, especially now per last week that we have pointers, which is painful as they might be to wrap your mind around sometimes. They really just let us point to different places in memory. And so we can start to stitch things together in an interesting way. So the only syntax we'll really need to do that to stitch things together in memory and build more interesting structures
are these things, struct, which allows us to represent structs already. And we did this with persons. And we played with this last time as well. And we saw it already for queues and stacks. The dot operator, we haven't used it that much. But recall that whenever you have a struct, you can go inside of it using the dot operator. And we did that for a person, person.name and person.number when we were implementing a very simple address book. The star was new last week. And it can mean different things in different contexts. You use it when declaring a pointer. But you also use it when dereferencing a pointer, to go there. But just so you've seen it before, it actually tends to be a little annoying, a little confusing to use star and dot together. You might remember one example last week where in parentheses I put star something. And then I used a dot operator to go there and then go inside the structure. Long story short, we'll see today that you
can combine simultaneous use of star and dot into something that actually looks like an arrow, something that vaguely looks like a foam finger that might be pointing from one place to another. So we'll see that actually in some code. So where can we take this? Well, let's implement the first of these ideas, namely something that's very canonical in computing known as a linked list. And let's see if we can maybe do this. How about Scully, could we get you to come on up and volunteer here?
So our friend Scully-- there's some cookies in this for you. So Scully has come prepared with a whole bunch of balloons to represent chunks of memory because we'd like to paint a picture here of what's involved in actually allocating space that's not necessarily contiguous and might be over there or over here or over here in the computer's memory. So, for instance, if I want to start allocating space one at a time for a list of numbers, Scully, could you go ahead and malloc one balloon for me? And in this balloon I'll store for instance, the number one ultimately. So we have a balloon here. We rehearsed this before. And these balloons are actually really hard to blow up and tie off quickly. So thank you. So here we have a chunk of memory. And I could certainly for instance go in here and store if I might the-- here we go. I could certainly go ahead here and store in this balloon, for instance, the number one. But in the world of an array, it would just be back to back to back.
And actually, frankly, why do we need the balloons even? I could just use these numbers, 1, 2, 3. But the problem doesn't indeed arise note, that when we want to put a fourth number, well where does it go? Well, again, just to paint a picture, ideally I might allocate space for four. But if this is my array of size 3 like where does it go? This is the point. We can't just put it next to the 3. Maybe there's room for the 4 over here. But we have to somehow connect these from one to the other. So, in fact, let's act that out. So if I instead use this balloon metaphor of just allocating space from wherever it is, can you go ahead and allocate like another chunk of memory for me? And here is where I'll now have a chunk of memory in which I can store the number computers a little slow. So in here, the second balloon I'll have a separate chunk of memory. AUDIENCE: Oh my gosh. DAVID J. MALAN: There we go. OK, good. Second chunk of memory, thank you, Scully. Now, I can certainly--
Thank you. I can certainly now store the number two in this chunk of memory. But it's not necessarily contiguous. This chunk came from over here as per Scully's position originally. This chunk obviously is coming from over here. And if you don't mind holding that for a moment, this is breaking the metaphor of an array, which was indeed contiguous. And even though I as the human can certainly go over and walk next to her, that's the equivalent of copying values from one place to another. What if we're a little more clever, though? And if Scully found space for this number one over here, let's just leave this balloon here. And if she found space for the number 2 over there, let's leave that balloon there. But we do somehow have to connect these numbers together. And here is where to-- I'll try to do this on the fly. Maybe I could do something like this. I can take this balloon here. And I can actually tie a string to it so that if I
want to connect one to the other, we can link these, if you will, together. And so here now I have a linked list that is not necessarily contiguous. There's a whole bunch of memory that may very well have real values, may very well have garbage values. But I've somehow now linked these two together. And maybe just as a final flourish, if we could blow up one more balloon to represent more space-- and now she's finding room for that balloon over there. Nice. This one is a Yale chunk of memory. So now I'll need one more link, if you will. And if I actually connect these two in this way, let me go ahead and tie this off here. Now I can go ahead and connect these two. If you never see this demonstration again in next year's videos, it's because this did not go very well. Here now we have the number one where we first malloced it, the number two roughly where we malloced it, and the number three-- OK, so maybe we'll fix this some other year.
Now, we'll have the number 3 allocated there. But the whole point of this silly exercise is that we can certainly use the computer's memory as more of a Canvas, put things wherever we want, wherever is available so long as we somehow connect the dots, so to speak and can make our way from one chunk of memory to the next to the next, thereby literally linking them together. But, of course, we're using balloons for this metaphor. But at the end of the day, this is just memory. So how could we encode one chunk to another chunk to a third chunk might you think? What's the trick? Yeah? AUDIENCE: Pointers. DAVID J. MALAN: Using pointers. That's why we introduced pointers last week. Because as simple as an idea as it is, as hard as it is to write sometimes in code, it's literally just a pointer, a foam finger pointing to another chunk of memory. And so these pointers really are metaphorically being implemented now in with these pieces of string.
So we'll have to debrief later and decide if we ever do this demo again. But thank you to Scully for participating. OK, we have plenty of-- OK, fair's fair. There we go. Thank you Scully. So let's now actually translate this to something a little more concrete and then get to the point where we can actually solve this problem in code. So here's that same canvas of memory. And if in this canvas of memory now I actually want to implement this idea of the number 1, the number 2, the number 3, let's stop tying our hands in terms of expecting our memory to be contiguous back to back and start to move away from using arrays.
So, for instance, suppose I want a malloc space for the number 1 just as I first asked of Scully. Suppose it ends up over there on the board. The important thing for discussion here is that that number one, wherever it ends up, is surely located at some address. And for the sake of discussion as in the past, suppose the number one just ends up at location 0x, 1, 2, 3. So 0x, 1 2, 3 is where Scully was originally standing right here. Then we asked for malloc for another chunk of memory. Suppose that it ends up over here at address 0x, 4, 5, 6. So that's maybe roughly here when Scully was standing in her second position. Lastly, we allocate the number 3. Maybe it ends up at location 0x, 7, 8, 9, which was again per Scully's third malloc roughly over here on stage. Now, this picture alone doesn't seem to lend itself to an implementation of the string, metaphorically, to the pointers unless we allow ourselves a new luxury.

Ask anything
We've read this whole study set, so questions about it get the best answers.