1. Home
  2. Explore
  3. Computer Science
  4. C Data Structures and Pointers

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

C Data Structures and Pointers

Transcript

[MUSIC PLAYING]

DAVID MALAN: All right, this is CS50. And this is our look today at data structures. You'll recall last week that we gave ourselves a few new ingredients and some new syntax in C. We introduced pointers, the ability to address chunks of memory by actual addresses-- 0, 1, 2, 3 and on up. And we introduced the star notation and a few other functions, malloc among them, free among them, so that you can actually manage your computer's memory. Just to hammer this home, let's take a look at just this small example that from the outset is buggy. This code is buggy. And we'll see in just a moment why. But let's just walk through it step by step. This first line highlighted in yellow in English is doing what as you understand it now? If you're a little rusty since last week, what's that first line of code doing in English? Anything? Yeah. AUDIENCE: It's creating a point to an int named x. DAVID MALAN: Perfect. It's creating a pointer to an integer and calling

that pointer or that variable x. And let me propose that the next line is doing the same thing giving us another pointer to an integer but this time calling it y. The third line of code, someone else, what's happening in English with this line here? Yeah. AUDIENCE: It's creates a memory of size of int and assigns it to x, but it's more difficult to execute if it's not a pointer, I don't know. DAVID MALAN: This is not the bug. But the first part is correct.

malloc is the function we introduced last week that allocates memory for you. It takes one argument, the number of bytes that you want to allocate. Even if you don't recall how many bytes you need for an integer, you can call this other operator, sizeof, that we saw briefly last week, that will return, in this case, 4 most likely depending on the computer that you're on. So this is saying, hey, computer give me 4 bytes of memory. And it returns that chunk of memory to conventionally by way of the first address, so ox something, wherever those 4 bytes happen to star. And then it stores that address in x, which is in fact OK, because as you noted initially, x is in fact a pointer. That is an address. So all this is doing is it's declaring a variable called x and storing in it ultimately the address of a legitimate chunk of memory. You wouldn't typically allocate an int like this. You would allocate an int with just int and semicolon just like in week 1.

But now that we have the ability to allocate addresses and allocate memory, you could achieve the same idea here. This line here now, the fourth line of code, says what in English? Star x equals 42 semicolon. What's going on there? Yeah. AUDIENCE: It goes to the address in the x and then sets it to 42. DAVID MALAN: Good goes to the address in x and sets it to 42. So the star operator is the dereference operator, which is a fancy way of saying go to that address. And what do you want to do? Well, per week 1 when we discussed the assignment operator, it just says put the number 42 there. So wherever malloc found 4 bytes of available memory for me, this fourth line of code says, go there and put the number 42 by putting the appropriate zeros and ones. This last line here-- and here's the bug, if we finally reveal it here-- this line is buggy. Does anyone see why? Yeah, over here. AUDIENCE: You haven't allocated memory for that variable yet. DAVID MALAN: Exactly.

I haven't allocated memory for that variable yet. And because up here I've just said int star y semicolon. You can only assume safely that has some garbage value, some unknown value, maybe remnants from some other part of the program, that might not necessarily be true here at the beginning of the program. But for safety's sake assume that if you don't give a variable a value, who knows what it contains. It's got some bogus address, such that if you say star y go to that bogus address something bad is going to happen. And maybe you experienced this already in P Set 4 or prior, some kind of memory problem with your code, or a segmentation fault or seg fault, bad things happen when you go to addresses that don't exist or that you don't even know where they are. So this line of code is bad. But we can do a little better. What if instead I do something like this? I actually assign to y x. So that just says put in y the same address that's in x.

And then with this last line of code, what if I now say star y equals 13? What is that-- you're nodding your head. What am I doing correctly now? AUDIENCE: Now there's memory allocated for y. DAVID MALAN: Good. Now, there's memory allocated for y. So you're saying go to that address and put 13 there. However, what did we just need to the 42, just to be clear? We clobbered it. We overwrote it with the 13. Because if x and y are the same address, both this says go to that address and put 42 there, but then two lines later, we say, no, no, no, go there and put 13 there instead. But long story short, bad things happen when you don't necessarily anticipate what is in memory and you don't allocate it yourself, so thanks to one of our friends at Stanford, allow us to take a moment here to hit Play on a short film, a claymation if you will, that paints the same picture in a more memorable way perhaps. If we could dim the lights. [VIDEO PLAYBACK] NARRATOR: Hey, Binky, wake up.

It's time for pointer fun. BINKY: What's that? Learn about pointers? Oh goody. NARRATOR: Well, to get started, I guess we're going to need a couple pointers. BINKY: OK, this code allocates two pointers, which can point to integers. NARRATOR: OK, well, I see the two pointers. But they don't seem to be pointing to anything. BINKY: That's right, initially pointers don't point to anything. The things they point to are call pointees. And setting them up is a separate step. NARRATOR: Oh, right, right. I knew that. The pointees are separate. So how do you allocate a pointee? BINKY: OK, well, this code allocates a new integer pointee. And this part sets x to point to it. NARRATOR: Hey, that looks better. So make it do something. BINKY: OK, I'll dereference the pointer x to store the number 42 into its pointee. For this trick, I'll need my magic wand of y dereferencing. NARRATOR: Your magic wand of dereferencing. That-- that's great. BINKY: This is what the code looks like.

I'll just set up the number. And-- NARRATOR: Hey, look, there it goes. So doing a dereference on x, follows the arrow to access its pointee, in this case, the store 42 in there. Hey, try using it to store the number 13 through the other pointer, y. BINKY: OK. I'll just go over here to y and get the number 13 set up and then take the wand of dereferencing and just-- [BUZZER SOUND] oh. NARRATOR: Oh, hey, that didn't work. Say, Binky, I don't think dereferencing y is a good idea, because, you know, setting up the pointee is a separate step. And I don't think we ever did it. BINKY: Oh, good point. NARRATOR: Yeah, we allocated the pointer y. But we never set it to point to a pointee. BINKY: Mm, very observant. NARRATOR: Hey, you're looking good there, Binky. Can you fix it so that y points to the same pointee as x? BINKY: Sure. I'll use my magic wand of pointer assignment. NARRATOR: Is that going to be a problem like before? BINKY: No, this doesn't touch the pointees.

It just changes one pointer to point to the same thing as another. NARRATOR: Oh, I see. Now y points to the same place as x. So, wait, now y is fixed. It has a pointee. So you can try the wand of dereferencing again to send the 13 over. BINKY: Uh-- OK, here goes. NARRATOR: Hey, look at that. Now dereferencing works on y. And because the pointers are sharing that one pointee, they both see the 13. BINKY: Yeah, sharing, whatever. So are we going to switch places now? NARRATOR: Oh, look, we're out of time. BINKY: But-- [END PLAYBACK] DAVID MALAN: All right, so now that we do have this power of pointers and addresses where we have low level access to the computer's memory, we can actually solve problems a lot more powerfully and in a lot more interesting ways. But first, let's motivate some of these problems. So back in Week 2, we introduced arrays, which was the first of our data structures, if you will.

Before then in Week 1, all we had was variables for things like ints and chars and floats and so forth. In Week 2, we introduced arrays, which meant you could store two ints altogether or three or 10 or 100. So you can kind of encapsulate lots of data together. So unfortunately, though, arrays aren't quite as powerful as might be ideal. So, for instance, if we have an array with size 3 and we actually want to go ahead and store three values in it-- one, two, three-- suppose that we actually want to now store a fourth value, but we didn't anticipate that from the get go. Recall after all that with arrays you have to declare their size upfront. So you've got to hard code the number 3 or a variable containing the number 3. But suppose that we want to store the number 4. You might think that, well, just give me another box of memory just to the right of the number 3, so that I can keep all of my numbers together.

But unfortunately, per last week, that's not really a reliable assumption, because in the context of the rest of your computer's memory, that 1, 2, 3, might be here surrounded by other bytes. And per last week those bytes might be mostly filled with other data from some other parts of your program. And yet you would think that in seeing that 1, 2, 3 is kind of painted into this corner, so to speak, that there's just no room for the number 4, and therefore you can't add the fourth number to your array, is there a solution visibly to this problem nonetheless?

Where else could we put it? Yeah. AUDIENCE: Move it to off of other memory. DAVID MALAN: Say that a little louder. AUDIENCE: We can move it off to other memory. DAVID MALAN: Yeah, so maybe we can move it off to other memory. So there's a lot of EMMAs in my memory per last week, but there is still, it would seem, based on this picture, some unused memory. So maybe we could resize our array, grow it, not by just moving all of the EMMAs because frankly that would seem to take a lot of time if we had to shift all of these characters, why don't we just relocate the 1, 2, 3 down here, and that gives us an extra space for at least a number 4. So indeed even if you're using arrays, you can achieve this outcome by actually moving memory around. But consider what's involved in that. So if you've got our old array at top left, and we've got our new array at bottom right, that is of size 4. So we have plenty of room. How do we go about resizing the array? Well, it's kind of an illusion.

You can't just resize the array when we have all of these EMMAs surrounding us. Instead, we actually have to move the array or copy it. So the 1 gets moved to the new memory. The 2 gets moved to the new memory. The 3 gets moved to the new memory. And then at that point, we can just throw away or free the previously used memory and now go ahead and add our 4. Unfortunately, this isn't necessarily the best strategy, right, because if these three lockers represent our original memory and these four lockers represents our new memory and they're deliberately far apart, that is to say that if I want to go ahead and move like these same numbers, I really have to do something like this, which involves quite a few steps. Let me go ahead and put the 1 in there now. Now, let me go ahead and get the 2 here. And then I can go ahead and put this in here. So now I've got the 2. And then lastly, I can go grab the 3. And so even though I did this pretty quickly on the screen,

the reality is there's a decent amount of work to do. And then I still, of course, have to go ahead and add the 4 to the mix, which is to say that I've taken figuratively and physically quite a few steps in order to resize an array from size 3 to size 4, which is to say if we now consider the efficiency or, if you will, inefficiency of that algorithm, what kind of running time is involved when inserting additional numbers into an array as I've done here?

Here's our menu of options from a couple of weeks ago when we focused on algorithms. What's the running time of insertion into an array based even on that simple demonstration would you say? What's the running time? Yeah. AUDIENCE: O n squared. DAVID MALAN: Say it again. AUDIENCE: O n squared. DAVID MALAN: O n squared. So maybe O n squared in that there was a lot of back and forth and we've seen that before. We've seen bubble sort and selection sort add up. It's not quite as bad as that. It's not quite as bad as that. Yeah. AUDIENCE: O of n. DAVID MALAN: O of n. And why do you say O of n? AUDIENCE: Because for as like as many lockers there are in the first one, you have to increment the same amount of processes to insert them. DAVID MALAN: Exactly. Whatever number of lockers you have here-- so that's three specifically-- but n more generally, it's going to take me n steps to transfer those numbers over here. Or technically, it's going to take me 3-- maybe if I go back and forth,

it's like 6 steps. But it's some multiple of n. So it's not n squared. That's when we kept iterating again and again and again. This time I just have to move 3 numbers to here and then add the fourth number. So it's indeed, Big O of n when you want to go ahead and insert or search equivalently an array that's actually implemented-- sorry, insert is going to take us linear time. But search recall-- and this was the powerful thing-- what's the running time of search so long as you keep your number sorted? Per two weeks ago, that was logarithmic. So we haven't necessarily sacrificed that. And that's the appeal of storing our data in an array that's sorted. You can use binary search. However, this is expensive and moving things around isn't necessarily the ideal approach. So let's just consider what this might look like in code. Let me go over to CS50 IDE here. And let me go ahead and create a new file called list.c.

And let's see if we can't represent in code exactly this idea. So let me go ahead and include for myself standard stdio.h just so that we can print out some values ultimately. Let me go ahead then and declare main-- int main void. And then down here, let's just arbitrarily start where we did with three integers, called list and size 3. So I'm just mimicking exactly where we started pictorially by having an array that was fixed at size 3. And then if I went ahead and initialized that list, I could just hard code-- that is type into the program itself-- those three values into bracket 0, 1, and 2 the numbers 1, 2, 3 respectively. So I'm just manually initializing that array to three values. And then just so that this program has some purpose in life, let me go ahead and do int i equals 0, i less than 3, i++. And then, let's just print out these elements just for good measure. Each of them is an int. So we'll use %i. And then I'm going to go ahead and print out list bracket i.

So kind of a Week 2 style program, where All I'm doing is hard coding an array of size 3, initializing it with three values, 1, 2, 3; 0 indexed, and then printing them out. So if I go ahead and save this and make my list and then go ahead and compile this with ./list, I should see hopefully 1, 2, 3. But there's a problem with this implementation fundamentally because I have hardcoded-- that is typed explicitly-- the size of this array, how can I go about adding a fourth element?

What would I have to do? Well, I could change the code up here to 4. And then I could add another line here. And then I could change this. But then I have to recompile it. And so it's certainly not dynamic. But we did see a function last week that lets you allocate more memory dynamically. And just to be sure what was that function? So malloc. Right? Now that we have malloc, you don't have to type into your program source code from the get go a fixed number. You can actually allocate some amount of memory dynamically. Now, here just for demonstration's sake, we'll do it to achieve the same goal, but in a way that's going to scale a little more effectively. Recall from last week that if you want to get a chunk of memory from malloc, it's going to return the address of that chunk of memory. So that suggests that I can declare a pointer to an integer called list. And then let me go ahead and allocate, how about, three integers initially

times whatever the size is of an integer. So this is a little weird looking, but consider what this is doing. malloc is being asked for 3 times the size of an int. So give me enough memory to fit three integers. By definition that returns a pointer, per last week. So we have to assign it to a pointer on the left. So list is a variable now, just like x and y from our previous example, that's storing the address of that chunk of memory. But what's cool about C is that now that you know that list is a chunk of memory, we can actually borrow that same square bracket notation from Week 2. And this code here doesn't actually need to change. If you use square bracket notation next to the name of a pointer, what's going to happen for you automatically is the computer is going to go to the first byte in that chunk of memory. This index is going to go to the next chunk of memory. This is going to go to the next chunk of memory,

all within the scope of what malloc returned for you. And just as an aside, how many bytes are in an integer? AUDIENCE: 4. DAVID MALAN: 4. And recall I briefly mentioned the expression last week pointer arithmetic. What you're also getting sort of magically with this square bracket notation is that bracket 0, it happens to be byte 0. Bracket 1 is not the second byte. It's actually 4 bytes over. And bracket 2 is not the third byte. It's actually 8 bytes over, because you allocated 4 plus 4 plus 4, 12 bytes. And so this square bracket notation just jumps you to the right place in that chunk of memory, so that you can fit int, int int. Yeah. AUDIENCE: Why do you allocate a pointer to an int rather than an pointer to an int array? DAVID MALAN: Why do you allocate a pointer to an int and not a pointer to an int array? In this context, arrays and pointers are in some sense the same. A pointer is an address of memory.

An array is just a chunk of memory. And so even though we used chunks of memory in Week 2 by just calling them arrays, they really are just more generally chunks of memory that support square bracket notation. But now that we can allocate as much memory as we want, we can kind of use these two concepts interchangeably. And there are some subtleties in C. But this now has the same effect as Week 2. And this is the only new line from this week. But now if you're using malloc, even though I'm not going to do it in a more complicated program here, you can imagine now the code running in a loop and maybe allocating more memory and more memory and more memory when you need it, because malloc allows you to do just that. And we do need to do a couple of safety checks here. It turns out, per last week, that malloc can sometimes run out of memory. If you're Mac or PC or the cloud runs out of memory for your account, well, you might want to check the return value.

And so good practice would be, well, wait a minute, if list equals equals null, let me just go ahead and return 1, something went wrong, because my computer is out of memory for some reason. So best practice would say anytime you allocate memory, always check if you've gotten back null. Now, let me just do something for the sake of demonstration. Let me move my window down here. Let me highlight these lines of code and just make the claim that highlighted here between lines 5 and 13 are lines of code that simply allocate a list of size 3 and store three values in it. That's the story where we left off a moment ago. Suppose now I change my mind and decide after line 13 or maybe elsewhere in this program if it were larger, you know what, I actually want another integer. I want to resize that array. Well, how can I go about doing it? Well, let me go ahead and do this. Let me go ahead and allocate, for instance, another address

and say store at that address a chunk of memory corresponding to four integers using the size of operator as before. So temporarily, let me go ahead and give myself a new chunk of memory that is big enough to fit four integers instead of just three. Let me practice best practices and say, you know what, just in case, if temp equals equals null because I'm out of memory, forget it, I'm done with the program. We're not going to proceed anyway. But that's just good practice now. But now what I want to do? If I now have two chunks of memory, this one is a size 3, this one is of size 4, what did we do the last time we wanted to move something around in the computer's memory, what did I physically do with the lockers? I think you're nodding. What did I do? AUDIENCE: You went through each and move 1 to the-- DAVID MALAN: Yeah, exactly, I went through each one and copied the value from left to right, from old to new. And so let me go ahead and do exactly that.

I think I can do this with a for loop, for int i get 0, i is less than 3, because that's the size of the old array that size 3, i++. And then in this iteration, I can just do something like this-- use this new chunk of memory just like an array, because I claimed I can use my square bracket notation and store location i whatever is in the original list at location i. So this code here now, if I were to comment it, copy integers from old array into new array. And that too is just using a for loop from old to new. But now that's not quite everything I want to do. I also want to store at the location 3, 0 index, which means it's the fourth location, another value, number 4. That's why I put the additional number 4 into those lockers. So now with these lines of code, I have implemented the physical notion of copying all of the values from the old array into the new array. So I'm almost done, except what did we learn

last week that you should do whenever you're done with a chunk of memory? Do I still need the original chunk of memory? AUDIENCE: No. DAVID MALAN: No. And how do I give it back to the computer? AUDIENCE: Free. DAVID MALAN: Free. So quite simply, I literally just call free, passing in the address of the chunk of memory that I want to free. And even though I'm passing in one address, the computer is going to do the heavy, lifting of remembering how many bytes I asked for originally. You don't have to worry about that. You just say, whatever this is pointing at, go ahead and free it all. So now, you know what, now that I've gotten rid of that list, I'm going to update list equal temp, which is just cleaning up the naming. Temp is kind of a stupid name for a list. Let me just reuse the original pointer and let list equal temp. And now down here if I've done everything correctly, it should suffice to print out that whole list. So let me save this.

Let me give myself a bigger terminal window. Do make list again. A lot of mistakes. Let's see, first one is up here. Implicitly declaring library function malloc dot dot dot. What generally is the solution when you see implicitly declaring something? AUDIENCE: Header file. DAVID MALAN: Header file, which one do I want? Do you recall? This is subtle and we might not have used it last time if I used the CS50 library, but it's stdlib.h. That is where malloc is. That is where free is. So stdlib.h is one new header file that contains last week's functions. So let me try this again. Let me make list. Nice, this time it did compile. ./list and-- hm, I seem to be missing that fourth number. But I think this is just a stupid mistake on my part. What did I do wrong if I look at the printing of this array? AUDIENCE: Size of list.

DAVID MALAN: Yeah, down here the new list is size 4. So frankly, if you recall a few weeks ago, I encouraged you, don't just hard code numbers, magic numbers, in your programs. We should really be using constants or some other variable. This is exactly why, because you, just like me, might overlook a detail like that. So let me recompile it. And let me do list. And, voila, there is my 1, 2, 3, 4. Now, to be clear, this is kind of a stupid program, because I sort of decided halfway through writing this program, wait a minute, I want four integers, not three. And, of course, at that point, you should just delete the earlier code you wrote. So this is just for demonstration sake. If you imagine this being a bigger program, that just over time the human decides maybe because get int is called that they need more memory, this is how you would do it using malloc. But it turns out there's a function that can actually

make our lives a little easier here. So let me go ahead and clean this up just a little bit. It turns out that I don't have to allocate more memory myself, copy all of these things myself, and then also free it. I can consolidate a bunch of these lines as follows. Instead of using malloc, I can actually say realloc, which as the name suggests, reallocate a chunk of memory. What do you want to reallocate? Well, I want to reallocate the list. And this time I want to do 4 times size of an int.

I'm going to store this in temp temporarily. I'm going to make sure that nothing went wrong, as by checking for null, which just means, hey, you might be out of memory. And then I'm going to return if so. But down here, if all is well, I'm going to go ahead and do this. And watch this I now have simplified my code by quite a few lines. realloc, by definition-- this is another function in stdlib.h-- handles the process of taking an existing chunk of memory that you already asked for, resizes it to be this new size, whether it's bigger or smaller. It handles the copying of the data from old to new to you. And you just need to check that nothing went wrong as by checking for null here and then remembering the new value. So this code now, which is just six lines of code, previously was more than that. And it's just a handy function to use. All right, a question from earlier. AUDIENCE: Why can't we just create this to the temp in the beginning,

because if we equate this to the temp, then we equate this to the pointer perhaps, so this to the point to the 4 bytes of memory? DAVID MALAN: Really good question. So let me roll this back by rewinding. And all of the finished versions are on the course's website if you want to play with them later. This was the previous version using just malloc. If you just do this, update a new chunk of memory, as I think you're asking, what's happening is you are effectively orphaning the old chunk of memory. Because if you change what's stored in list and have it store the new chunk of memory, where'd the old chunk of memory go? It's sort of floating there in your computer's memory. But you've lost all pointers to it. There's no arrow anymore pointing to it conceptually. So that's why we have to jump through these hoops of having a temporary variable just so that we don't lose track of things we've allocated.

And we'll see this later today with another data structure as well. Yeah. AUDIENCE: Somebody asked this, but I don't understand that if you initialize temp as a pointer toward integer, then does it not create problems that you use it as an array. DAVID MALAN: Good question. If you initialize temp as a pointer to an integer, does it not create problems that you're using it as an array? Short answer, no, because again an array by definition from Week 2 is just a chunk of memory. And in C you can use the square bracket notation to jump to random parts of that memory using simple arithmetic, bracket 0, 1, 2, and so forth. Last week when we introduced malloc and free and now realloc, you now have a more low level way of allocating as much memory as you want. So it's a more powerful, general purpose mechanism. But at the end of the day, you're still getting back a chunk of memory, contiguous memory, bytes that are back to back to back.

So you can certainly still use the square bracket notation because essentially an array is a chunk of memory. And malloc gives you a chunk of memory, ergo you can treat it as an array. They really are equivalent in that sense. You just don't get as many user friendly features as with arrays, like them being freed for you, as we never until last week do we have to free chunks of memory. Arrays do that for you automatically thanks to the compiler. Yeah. AUDIENCE: Do you not have to recreate the list for temp after line 37. DAVID MALAN: Yes. Thank you. So there is a bug here. And if I ran Valgrind on this code, I would see exactly that, that I'm leaking some number of bytes. So indeed, at the end of this program, I want to free the-- let's make sure-- yep, I want to free now the new chunk of memory, which is a size 4, to avoid exactly the problem you identified. Good catch. All right , so just for now, even if that's a lot of code,

let's consider now higher level takeaways from this, just so that we can then motivates an alternative approach that allows us to stitch together somewhat fancier data structures instead. So in general, a data structure is just a programming construct in C, C++, Java, Python-- we'll see them in different languages over the remainder of the term-- that allow you to store information differently in your computer's memory. In C, everything we're about to do today is thanks to these three features of C. So even though this may feel like a lot of syntax, everything we do today boils down to three pieces of syntax that you have seen before. Struct, this recall was a keyword in C that allows you to create your own structure. For instance, a couple of weeks ago, we created a person structure, who had a name and a number. And that gives us our own data type that is structured to contain two values, like name and number.

You use structures as well for the problem set involving bitmaps, the bitmap header and so forth. Those were data structures as well. What do we use the dot notation for just to be clear? And you definitely use this when manipulating red and green and blue pixels recently. Yeah. AUDIENCE: To access a property of a structure. DAVID MALAN: Exactly. To access a property of a structure. So if you want to get at a person's name or get at a person's number, you use the variable's name and then a dot operator to get inside of that data structure. So we've seen that before. Then last week and again today, we see the star operator, which can kind of mean different things in different contexts. But it's always related here to memory as of last week. This is the dereference operator that allows you to go to a chunk of memory by way of this thing called a pointer. So even if today feels like a bit of that fire hose--

and again per my email, this is where things now begin to level off-- realize that it all boils down to first principles, or if you will sort of three scratch-like puzzle pieces that we're now going to assemble into more interesting solutions to problems. So allow me to introduce something called a linked list. A linked list, as we'll see is going to allow you to store a list of values. Now an array allows you to store a list of values. But what are some of the downsides with an array? Well, an array is a fixed chunk of memory. And if you want to resize that array to add more values to it, what do you have to do? Well, you minimally have to allocate more memory. You need to copy all of those values from old to new. And then you can go about your business. Now, realloc is a function that makes that a little simpler. But realloc is doing the exact same legwork that I was doing between the lockers of copying value, freeing memory, and so forth. So it needs to be done.

And that's why insertion into an array is going to be big O of n, because it might take you that much time to copy the whole array into a new space. So that feels kind of suboptimal, right? Arrays can be slow in that sense. But what was the appeal of an array? Like what's good about arrays? Because we don't want to abandon them entirely. Yeah. AUDIENCE: You can index into them really easily. DAVID MALAN: You can index into them really easily, not only syntactically with the square brackets, but you have constant time access-- this is known as random access. And it's not random in the sense that you just end up who knows where. You can just jump to bracket 0 or 1 or 2 instantly. It took me, the human, more time because I had to physically walk. But a computer is going to be able to jump to 0, 1, 2, 3 instantly. And so arrays are super fast. And they lend themselves to things like binary search as we've seen now for some time.

But what if we use the canvas that is our computer's memory like a little more cleverly? We don't have to just plop things next to each other, next to each other, next to each other, and then hope for the best hope that there's still more memory back to back to back. What if we instead are a bit more clever about it? And suppose we want to store the number 1. And that happens to be an address 0x123. It's arbitrary. But recall from last week that every byte of memory in your computer is stored somewhere. So let's propose that 1 is stored at 0x123. Suppose now that this represents an array of size 1 and you want to add a second value to this array. Or let's start calling things more generally a list. A list like in the real world is just a list of values. This list is of size 1. Now maybe there's a lot of EMMAs in this memory that are getting in the way. But suppose that there is some free space a little lower in your computer's memory over there. So it's not here.

It's not here. It's not available here or here or here. There's other stuff there. But suppose the computer does have some available memory over here in which you can store the number two, just because. And that address happens to be 456. Finally, you want to store third value. And it turns out that the nearest possible location is down here, number 3. That happens to be at address 0x789. So this is not an array by definition, because the 1, the 2, the 3 are not contiguous back to back to back. You cannot square bracket notation here because square bracket notation requires, per Week 2, that all of your values be next to each other, just like the lockers here. This picture, where 1 is over here, 2 is over here, 3 is over here is more like, oh, maybe this is 0x123. Maybe this is 0x456. Maybe this is 0x789. They're kind of all over the place. And that's just because that's what's available in your computer's memory. But what if I get a little extravagant and I

start to use, not just one chunk of memory to store each value, like 1, 2, 3, what if I go ahead and give myself twice as much memory just to give myself some flexibility? So I now conceptual use this chunk of memory to represent one. This junk to represent 2, this chunk to represent 3. But you know what I'm going to use the latter half of each of those chunks for? Any thoughts? AUDIENCE: Address to the next. DAVID MALAN: An address to the next chunk of memory. So, for instance, if my goal is to keep this list sorted, so I want conceptually to have a list that stores 1, 2, 3, why don't I use this as sort of a map or a breadcrumb, if you will, that points to the next chunk of memory? And why don't I use this chunk of memory to point at the next one? And then this chunk of memory, you know what, I just need a special value here. What would be a good arbitrary way to say, mm, mm, there's nothing more in the list? AUDIENCE: Null.

DAVID MALAN: It's something called null. And this technically is different from backslash 0, which is a char. This is something called-- well, this is in hexadecimal 0. Now, starting today-- and we saw the super briefly last week-- this is n-u-l-l with two L's-- this was stupid left hand not really talking to right hand-- n-u-l is backslash 0, which is a char. n-u-l-l is a pointer. But they both equal 0 underneath the hood. So you just store special value that says that's it for the list. Now, we last week I proposed who really cares where things are in memory? So indeed, let's do that again. Let's just use pointers drawn as arrows in this artist's rendition to say this list of numbers, 1 2, 3, is now linked. A linked list is just a data structure containing multiple chunks of memory that are somehow linked together. And if underneath the hood, so to speak, they're just linked together by way of pointers, and the price we pay is

that rather than now in a linked list storing just the numbers 1, 2, 3, which we could have in an array, now you have to store twice as much information, 1, 2, 3, as well as three pointers, two of which are in use, the other of which is ready to go if I want to add something to this list. So this is to say we can now create structures that look like this in the computer's memory just by using this new feature of pointers. What might these structures look like individually? Well, any one of these numbers has two fields it seems. One is an integer. We'll call it number. And then there's another field here. That let's call it next by convention, but we could call it anything we want. It's just another chunk of memory that's pointing to the next element in the list. Well a couple of weeks ago, we introduced persons. And a person had a name and a number. That's not relevant today, because we're not dealing with names and numbers. We're just dealing with integers.

So let me propose that we back that up and still use the same syntax as a couple of weeks ago. But instead of defining a person, let's call this rectangle a node. So this is a term of art in computer science node-- n-o-d-e-- just represents this rectangular concept, a chunk of memory that you're using for interesting purposes. It's sort of a node in a graph if familiar from math. But what do I want this know to store? Well, let me go ahead and store a couple of things in it. One, a number, and that's just going to be an int. And I'm going to go ahead and call it number. And then any guesses as to what the second field should be declared as? I want to call it next just because it's conventional. What should its data type be? Any thoughts? Yeah in back. AUDIENCE: A pointer. DAVID MALAN: A pointer. And a pointer to what would you say? AUDIENCE: The next number. DAVID MALAN: A pointer to the next number, and not quite the next number

per se, because now we have not numbers only, we now have nodes. So those three yellow boxes, 1 2, 3, those are now nodes, I would say. So you know what? Let's go ahead and call this node star. But you can't technically quite do this. It turns out that C, recall, takes you super literally. And notice, if you read this code top to bottom, left to right, at which point in the story does the word node come into existence? Like not until the very last line. That's where we mentioned person. This is where we mentioned node. So, unfortunately, you can't use a node inside of a node, because it literally doesn't exist in the computer's mind until two lines later. So there's an alternative here. There is a solution. It's a little more verbose. Instead of just saying typedef struct, you actually say typedef struct node. Just add the word that you want to use. And now down here, you can say struct node star next. It's kind of like a work around. This is the way C works.

But this is the exact same idea. This means that any node in the data structure, any yellow rectangular box has a number and a pointer. And that pointer by definition is a pointer to a node structure. We just have to express it more verbosely here, because the shorthand notation node doesn't exist until the bottom. It's just sort of an annoying reality of the syntax. All right, any questions on that definition of struct? Yeah. AUDIENCE: Do you have to put node twice?

DAVID MALAN: Do you have to put node twice? You don't have to put node twice. You can actually use any word here you want. You can call this x or y or z. But then you're going to have to make this be struct x or struct y or struct z. By convention, I would just reuse the same term. So this is the formal name for this structure. It is a struct node. This is the nickname for the structure, more succinctly, node. And that's what typedef does. It gives you an alias from struct node to just node, just because it's easier to type elsewhere in the program. Other questions? All right, so what can we do now with this structure? Well, let's go ahead and build something up here. All right, so this is about as scary as the code gets today. We'll focus primarily on pictures and concepts hereafter. But let's take a tour through one implementation of this same idea of a linked list. How would we go about representing a linked list initially? Well, initially the list is empty.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent