1. Home
  2. Explore
  3. Computer Science
  4. Memory and Pointers

Study methods

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

Memory and Pointers

Transcript

[MUSIC PLAYING] SPEAKER 1: This is CS50. And perhaps not unlike past lectures, today is going to feel a bit like a fire hose again, but realize that it's going to be a lot less code today. So there's less syntax, just a few new ideas here and there. And the goal ultimately today really is the concepts and the ideas that we take away. And keep in mind that over the remainder of the semester, we will continue to apply and reapply these same ideas. So the goal today really is exposure.

And the goal for the semester is comfort. So with that said, let's consider where we left off last time, which was to consider that inside of our computer. Of course, we have memory. We have RAM, Random Access Memory. And it was convenient, we found, to start to divide this up into individual bytes. Like, byte 0 might be in the top left, and 2 gigabytes, 2 billion bytes, might be all the way down there in the bottom right-hand corner. And once we started to layout our memory, both conceptually and technologically, in this way, left to right, top to bottom, we had the ability to use a data structure of sorts. We introduced, recall, arrays, whereby if we think of our memory as just a grid of bytes, we can start using it kind of to our advantage to solve problems. And it turns out that perhaps a physical incarnation of this idea of an array might be like these red lockers here. Because even though you and I, every time we've looked at arrays thus far,

can kind of get a bird's-eye view of everything that's in the array, computer's actually pretty limited. It doesn't have that instant detection that you and I have when we just scan a list of numbers and [? kind ?] of take it all in. A computer is only going to be able to look at the contents of an array step by step by step, consistent with this whole idea of an algorithm. A computer can't just look at all the numbers and take it all in. It can only open, so to speak, one of these lockers at a time. So toward that end, we've gone ahead and populated these lockers with a whole bunch of numbers. And the goal at hand is to solve the problem. The goal at hand is to find one of those numbers. So if we distill computer science into this problem-solving mechanism, the input today is these seven lockers. And the output is going to be a Boolean, true or false, is the number we're looking for among those seven lockers?

And so rather than my kind of poking around looking for this number, might I call on, say, two volunteers to kick us off with two, say, algorithms? Let's see. Over here? Yeah. And let's go over here in front, if we may. Come on up. And what are your names? AUDIENCE: [? Nizari. ?] SPEAKER 1: Lizari? AUDIENCE: [? Nizari. ?] SPEAKER 1: [? Nizari. ?] OK, David. Nice to meet you. Come on up, [? Nizari. ?] And over here, what's your name? AUDIENCE: Eric. SPEAKER 1: Eric, OK. David. And come on up, Brian, as well. Nice to meet you, Eric. Eric, [? Nizari. ?] [? Nizari, ?] Eric. [APPLAUSE] Come on over here. So you came on up the stage first. Would you like to go first or go second? AUDIENCE: I'll go second. SPEAKER 1: You're going to go second. So Eric, you're up first. Come on over here, if you would. So Eric, behind these seven doors we have placed, in advance, the number 50. And we would simply like you, the computer, to search this array for the number 50.

AUDIENCE: Is it sorted? SPEAKER 1: I cannot answer that question at this time. Go. Oh, and so that the audience knows what's going on, if you wouldn't mind taking the numbers out to see. AUDIENCE: This is seven. SPEAKER 1: Excellent. Not 50. AUDIENCE: Should I-- can I take it out? SPEAKER 1: At this point, yes, you may do whatever you want now. Just find us 50. AUDIENCE: Two. [LAUGHTER] SPEAKER 1: Very good. AUDIENCE: One. SPEAKER 1: Nice. AUDIENCE: Six. SPEAKER 1: Very good. AUDIENCE: Three.

SPEAKER 1: Nice. AUDIENCE: None of these are close to 50. SPEAKER 1: No, none of them are close to 50. AUDIENCE: Four. SPEAKER 1: Four? And? AUDIENCE: 50! SPEAKER 1: Amazing! Very well done. [APPLAUSE] Very well done. Now, if I may, Eric, what was the algorithm via which you found us the number 50? AUDIENCE: Linear search. SPEAKER 1: OK, linear search, meaning what to you? AUDIENCE: You just go in a line, starting from there until there. SPEAKER 1: OK, that was a very sophisticated answer to a term we've not yet introduced. And that's great, linear search from left to right, so literally following a line. And was your algorithm correct, would you say? AUDIENCE: Yes. SPEAKER 1: OK, so it was correct. But there's these different parameters that we want to optimize solutions for not just correctness, but what other property as well? AUDIENCE: Design. SPEAKER 1: So maybe design, right, the efficiency. So was that the most efficient you could have done?

AUDIENCE: Actually, yeah, I think so. [LAUGHTER] SPEAKER 1: And why do you say that? AUDIENCE: Because-- so the numbers are sorted. So at the end of the day, I have to look through every single one. SPEAKER 1: Yeah. AUDIENCE: And it's just by chance that the 50 was at last. SPEAKER 1: Exactly. So it's unfortunate that they were all random. And I didn't want to tell you because I didn't want to bias your algorithm one way or the other. But not knowing if they're sorted and them not even being sorted means that that is the best you can do, look at all of the doors to find the number in question. And maybe you could have gotten lucky, if we had put 50 here. But in the worst case, Eric was, of course, going to have to do exactly that, searching all of the boxes. So thank you, Eric. Stay on stage with us, if you would, for a moment. And a round of applause, if we could, for finding 50 so well. [APPLAUSE]

[? Nizari, ?] could you come on up? We need you not to look at the numbers, because Brian needs to do a little bit of magic. And he's going to put some of the numbers back into the locker. So literally everyone in the room will know what's going on except you, at the moment. But we're going to give you the added bonus this time of sorting the numbers in advance. So Brian is in the process of sorting some numbers for us. The goal at hand, in just a moment, is still going to be the find the number 50. I'm really just stalling right now because he's still doing this. So I don't really have anything interesting to say just yet. Brian's back now. Hold on. And would you like to introduce yourself maybe? AUDIENCE: I'm [? Nizari. ?] SPEAKER 1: [? Nizari, ?] and what year are you? AUDIENCE: I'm a high school student, a senior. SPEAKER 1: Wonderful. At what school? AUDIENCE: Cambridge Rindge and Latin, it's down the street. SPEAKER 1: Just down the road.

So glad you can join us here today. And perfect timing, if I may. Now we have seven lockers here behind you. And the goal now is to still find the number 50. But I'm going to tell you that the numbers are sorted. So what's going to be your algorithm, if not the same as Eric? AUDIENCE: I will start-- SPEAKER 1: And here you go. AUDIENCE: I'm going to start in the middle. SPEAKER 1: All right, go ahead and show us what's in the middle. AUDIENCE: Middle number is seven. SPEAKER 1: All right. And now what's your next step going to be? AUDIENCE: So I want to get to 50. So assuming that they're sorted, I'm going to go this way. SPEAKER 1: Go to the right, OK. So we have three lockers remaining on the right-hand side. What's your instinct now? AUDIENCE: Mm, I'm going to start with this locker. SPEAKER 1: OK, this one being in the middle of those three. And you find? AUDIENCE: And we got 81. SPEAKER 1: 81. AUDIENCE: So I know that's too big. SPEAKER 1: Way too far.

AUDIENCE: Hoo, so I'm going to go with this one. SPEAKER 1: Which is now in the middle of the two lockers. AUDIENCE: And I got 50. SPEAKER 1: And a round of applause, if we could, for [? Nizari. ?] [APPLAUSE] Congratulations and thank you to you both. So thanks to you both. So here were two algorithms, dubbed linear search and binary search. And that's all we have for you right now. [LAUGHTER] So linear search and binary search are aptly named for exactly the reasons we saw. Eric literally walked across in a line looking for some element, where [? Nizari, ?] instead, actually used binary search, "bi" meaning two, and being very reminiscent of our discussion of phone books in week 0, when I did this divide-and-conquer approach. That, too, was called, even though I might not have labeled it as such, binary search because I kept dividing the problem in two, hence the "bi" in binary. Binary search was again and again and again,

just as we did here when searching for 50 the second time around. So these, of course, are two algorithms. But let's now start to formalize this discussion a little bit and consider how it was each of them was able to solve the problem correctly and then ultimately with better design. So linear search, we might distill as pseudocode like this and again, pseudocode, English-like syntax, no one way to write this. Eric, if I can put words in your mouth, might have done this. You might have thought to yourself for [? i ?] from 0 to n minus 1, to very quickly kind of map it to the idea of code, where this is locker 0, and this is locker n minus 1 or 7 or 6, specifically, in this case, with 7 total lockers. He then checked if the ith elements-- ith just meaning the one he's currently looking at-- happens to be 50, then go ahead and return true, the bool that was meant to be the output of this algorithm. And he kept doing that and doing that and doing that.

But suppose 50 were not there. And suppose he got all the way here, to where there is no locker. What should he ultimately return? AUDIENCE: False. SPEAKER 1: So false. And so the very last step of this algorithm not inside of that loop has to be kind of a catch all, where you just say, return false. If I got all the way through this loop and didn't find it, it must be the case that 50 is simply not there. So that might be one way to write the pseudocode for this problem. But now let's consider for a moment just how efficient or inefficient that code might have been vis a vis the second algorithm, [? Nizari, ?] where she actually divided the conquer in half in half in half. That, of course, was called binary search. And we can write this in any number of ways as well. But in pseudocode, I might propose this. Look right in the middle, just as she did. And if that number is 50, what should she have returned or outputted? AUDIENCE: True.

SPEAKER 1: So true as our bool. And so we might have done this, else if 50 were less than the middle item. She probably wanted a search to the left, just as when I was searching for Mike Smith, I might have gone left or right. So if 50 is less than the middle item, she might want to search the left half. Meanwhile, if 50 is greater than the middle item, then she might want to search instead the right half. But there is a fourth possibility, just to be safe here. What else might be the case? It's not in the middle, and it's not to the left, and it's not to the right. So it's just not there. And so there's actually a fourth case, and we can express this differently. I'm going to go ahead and just say at the top if there's no items in the list, let me go ahead and just claim return false. There's nothing there. After all, if I keep dividing a list in half and half and half and half, eventually there's going to be no list left.

At which point, I should just conclude, oh, it clearly wasn't there. If I halved it so many times, nothing is left on the right or the left. So how might we now think of this? Well, just as in week 0, we had a picture like this. And we claimed that these algorithms were either linear in nature, literally a straight line, like Eric's, or a little more curved or logarithmic, so to speak, like [? Nizari's. ?] And these had fundamentally different shapes. And we refer to them really by the number of steps they might take in the worst case. If the phone book or today, the number of lockers was n in total, it might take as many as n steps for Eric or anyone to find Mike Smith or the number 50 from left to right. If in week 0, I did two pages at a time, you can actually speed that up, but the shape of the line was the same. Eric didn't do that here, but he could have. With two hands, he maybe could have looked at two lockers at once.

So that might have been an intermediate step between those two extremes. But logarithmic was this more curved shape. But today, we're going to start to formalize this a little bit so that we don't keep talking about searching and binary search in linear search alone, but other algorithms as well. And computer scientists now actually have terminology with which to describe algorithms and just how well designed your algorithm is or how well implemented your code is. And it's generally called big O, literally a capital, italicized O. Big O notation just means on the order of. So if you were asked by someone what is the efficiency of your algorithm or the efficiency of your code, you could kind of wave your hand, literally and figuratively, and give them an approximation of just how fast or slow your code is. So instead of saying literally n steps or n/2 or log n steps, a computer scientists would typically say, ah,

that algorithm is on the order of n or on the order of n/2 or on the order of log n. So this is just cryptic-looking syntax that you pronounce verbally as "on the order of." And it's kind of written like a math function, just as we have here. But it turns out that when you're using big O notation, it really is kind of hand-waving. Like, it's just meant to be an approximation. And you know what? In this case here, these lines are so similar looking, I'm actually going to throw away the divided by 2. And we'll see why this is OK in just a moment. But those are so similar that I'm just going to call them the same thing. And it turns out-- and it's fine if you don't recall logarithms too well-- the base 2 there it doesn't really matter. I'm going to throw that away. It can be base 2 or 3 or 10. They're all within multiples of one another. So that's no big deal either, I claim. And if you don't recall, that's OK, too.

But the reason I claim that this red line and this yellow line are essentially the same thing is because if the problem gets big enough, that is the size of the problem gets bigger and bigger, and I only have so much screen here-- so let me instead just zoom out so that we see more y-axis and more x-axis. Notice how much closer the yellow and red lines even get to one another. And honestly, if I kept zooming out so that we could see bigger and bigger and bigger problems, these, frankly, would look pretty much the same. So when a computer scientist describes the efficiency of an algorithm, they say it's on the order of n, even if it's technically on the order of n/2. And here, too, on the order of [? law, ?] [? again ?] irrespective of what the base is. So it's kind of nice, right? Even though it looks a little mathy, you can still kind of wave your hand and approximate just a little bit. So there are different algorithms, though, in the world.

And here's kind of a cheat sheet of common running times. A running time is just how much time it takes for your program or your algorithm to run, how many seconds does it take, how many seconds does it take, how many steps does it make, whenever your unit of measure is. And we'll see on the list here some familiar terms. If I were to label this chart now with a couple of the algorithms we've seen, linear search, we'll say, is in big O of n. In the worst case, Eric is going to have to look at all of the lockers, just like a few weeks ago I had to look at all of the pages in the phone book maximally to find Mike Smith. And just to be clear, where's binary search going to be in this list of running times? AUDIENCE: Log n. SPEAKER 1: Log n. So it's actually better. Lower on this chart is better, at least in terms of time required, than anything above it. So we've seen this thus far. And now this sort of invites the question, well,

what algorithms kind of go here or here? Which ones are slower? Which ones are faster? That'll be one of the things we look at here today. But computer scientist have another sort of tool in the toolkit that we want to introduce you today. And this is just a capital Greek omega, this symbol here. And this just refers to not a-- it's the opposite of big O, if you will. Big O is essentially an upper bound on how much time an algorithm might take. It might have taken Eric n steps, 7 lockers, to find the number 50 because of linear search. That's big O of n, or on the order of n. That's an upper bound, worst case in this scenario. You can use omega, though, to describe things like best cases. So for instance, with Eric's linear search approach in the worst case, it could have and it did take him n steps, or 7 specifically. But in the best case, how few steps might it have taken him? Just one, right? He might have gotten lucky, and 50 might have been just there.

Similarly, when [? Nizari, ?] when she looked for 50 in the middle, how few steps might she have needed to find 50 among her 7 lockers? AUDIENCE: One. SPEAKER 1: One step, too. She might have just gotten lucky because Brian might have just, by coincidence or design, put the number 50 there. So whereas you have this upper bound on how many steps an algorithm might take, sometimes you can get lucky. And if the inputs are in a certain order, you might get lucky and have a lower bound on the running time that's much, much better. So we might have a chart that looks like this. This is the same function, so to speak, the same math. But I'm just using omega now instead of big O. And now let's just apply some of these algorithms to the chat here, then. Linear search is in omega of what, so to speak, by this definition? AUDIENCE: Omega 1. SPEAKER 1: Omega of 1, right? In the best case, the lower bound on how much time linear search might have taken Eric would just be one step.

So we're going to call linear search omega of 1. And meanwhile, when we did binary search, secondly, it's not going to be log n in the best case. It might be also omega of 1 because we might just get lucky. And so now we have kind of useful rules of thumb for describing just how good or bad your algorithm or your code might be, depending on, at least, the inputs that are fed to that algorithm. So that's big O, and that's omega. Any questions on these two principles, big O or omega? Yeah?

AUDIENCE: [INAUDIBLE] no matter where it starts [INAUDIBLE]?? SPEAKER 1: Really good question. And we'll touch on a few such algorithms today. But for now the question is, what's an example of an algorithm that might be omega of n, such that in the best case, no matter how good or bad your input is, it takes n steps? Maybe counting the number of lockers, right? How do I do that? 1, 2, 3, 4, 5, 6, 7-- my output is 7. How many steps did that take?

Big O of n because in the worst case, I had to look at all of them, but also omega of n because in the best case, I still had to look at all of them. Otherwise, I couldn't have given you an accurate count. So that would be an example of an omega of n algorithm. And we'll see others over time. Other questions? Yeah? AUDIENCE: [INAUDIBLE] omega or [INAUDIBLE] better omega value or a better O value? SPEAKER 1: Really good question. Is it better to have a really good omega value or a really good O value? The latter, and we'll see this over time. Really what computer scientists tend to worry about is how their code performs in the worst case, or maybe not even that, in the average case. Typically, day today, best case is nice to have. But who really cares if your code is super fast when the input happens to be sorted for you already? That would be a corner case, so to speak. So it's a useful tool to describe your algorithm.

But a big O and upper bound is typically what we'll care about a little more. So let's go in and make this a little more real. Let me go ahead and switch over to CS50 IDE. And let me go ahead and create a program here called numbers.c that's going to allow us to explore, for instance, linear search. So numbers.c is going to start off with our usual lines. So I'm going to go ahead and include cs50.h. I'm going to go ahead and include standard io.h, int main void, so no command line arguments for now. And in here, let me go ahead and just declare some numbers, maybe six numbers total. And if I want to declare an array of six numbers, recall from last week, I can literally say this. And if I want to initialize those numbers, I can do numbers bracket 0 gets, for instance, the number 4. Numbers bracket 1 gets the number, say, 8. Numbers bracket 2 gets the number 15. Numbers-- OK, so this is getting really tedious. Turns out in C, there's a shorthand notation

when you know in advance what values you want to put in an array. I can actually go up and do this, 4, 8, 15, 16, 23, 42 with curly braces on either side. So this is just what's called a statically initialized array. You just know in advance what the values are. And so I can just save some lines of code that way. But it's the same thing as the road I was going down a moment ago. But the curly braces are new for that little feature. Now I'm going to go ahead and iterate over these. So for int, i gets 0, i less than 6. And I'm going to cut some corners now so that we focus on the new stuff and not on the old. I'm hard coding 6 instead of using a constant or something like that. But all I want to do ultimately is search for the number 50. So what code can I now write inside of this for loop to just ask the question, is 50 behind this door? Someone want to call it out? Yeah? If? AUDIENCE: Number i [INAUDIBLE].

SPEAKER 1: Numbers i equals and not just single equals, but equals equals 50. I can go ahead now and return some answer. So I'm going to go ahead [? and say ?] printf, for instance, found in a new line. And then if I want to say that, no 50 was found, recall, that I want to do this outside of the loop, just like in my pseudocode earlier. So not found can go way down there. So just to be clear, what algorithm have I implemented here? AUDIENCE: [INAUDIBLE]. SPEAKER 1: Yeah. So this is linear search. This is the code incarnation of my pseudocode in Eric's actual execution of his algorithm. So let me go ahead and save this. Let me go ahead and make numbers, no error messages, which is good, dot slash numbers and Enter, or I should see what when I hit Enter here? AUDIENCE: Not found. SPEAKER 1: Hopefully not found because indeed 50 is not among those numbers. So that's interesting, but it's mostly warm up from last week. Why don't we consider a different problem,

where now we might want to search not just for numbers, but maybe names. Like, if the goal is to search a phone book, let me go ahead and create names.c that allows me to search now for names in an array. So let me go ahead and include cs50.h. Let me go ahead and include standard io.h. Let me go ahead and do it int main void. And then down here let me go ahead and give myself an array, so an array of string called names. I'm going to go ahead and give myself four names. And just like last time, I can do names bracket 0 gets Emma. Or again, to save myself time, I can cut a few corners here and say Emma, Rodrigo, Brian, David, just like last week, capitalized just because. So that's another way of writing the same code as with more lines than that. Now I'm going to do int i gets 0. i is less than 5, in this case, i plus plus. And now things get a little interesting because I might want to say if names bracket i equals equals-- let's not search for 50 now.

Let's search for Emma, just like last week. I want to go ahead and say found if I find Emma, else down here I want to say not found. The catch is that this will not work. Sorry. It's a little warm up here today. The catch is this will not work, even though I'm pretty much doing exactly what I did last time. What might the intuition be, especially if you've never studied C before, as to why line 10 here won't actually work as easily as numbers did a moment ago? Yeah?

AUDIENCE: Difference in data type. SPEAKER 1: Difference in data type, and what do what are the differences, to be clear? AUDIENCE: [INAUDIBLE] SPEAKER 1: Yeah. AUDIENCE: [INAUDIBLE] of the array [INAUDIBLE].. SPEAKER 1: Exactly. You can't use equals equals 4 strings because, remember, a string is not a data type, like a char, a bool, a float, an int. Remember, it's actually an array and an array that likely has multiple characters. And odds if you want to compare two strings, you probably intuitively need to compare all of the characters in those strings, not just the whole thing at once. In other languages, if you use Python or Java, you can actually do this in one line, just like this. But in C, everything is much more low level. If you want to compare strings, you can't use equal equals. However, it turns out there's a function, and you might have even used this in p-set 2, if you took this approach, where you can actually compare two strings.

So I'm going to delete this line and instead say, str comp, for string comparison, names bracket i being the first string I want to compare and then, quote unquote, "Emma" being the second string that I want to compare. And you would only know this from having been told it or reading in the documentation. This function str compare returns 0 if two strings are the same. It happens to return a positive number if one comes after the other alphabetically or negative number if one comes before the other alphabetically. But for today, we're just using it to test equality of strings, so to speak. So let me go ahead and save this. Let me go ahead and scroll up here and do make names this time. And unfortunately, I can't just use this function, it seems. And while it's fine certainly to keep using help 50 to understand these messages, any thoughts as to what I've done wrong? AUDIENCE: [INAUDIBLE] SPEAKER 1: Yeah.

I mean, I can't quite understand all of the words on the screen, frankly, at first glance. But string.h is something we've seen before. And indeed, if you read the documentation or the manual page, you'll see that str compare, indeed, comes in string.h so I need to put this up here. And now if I save my file and recompile my code down here with make names, now it compiles. And if I do dot slash names, I should see, hmm, interesting, a mixed message, literally. So is Emma there or not there in my array?

She's obviously there. And yet she's somehow not there. So what have I done wrong logically. Yeah? AUDIENCE: Do you have [INAUDIBLE] if it's found or not. So [INAUDIBLE] is not found [INAUDIBLE]. SPEAKER 1: Yeah. So it's this not found that I'm just blindingly printing at the end as a sort of catch all. But really, if I execute found or print found up here, what should I really be doing maybe right after that? Returning. And we looked at this last week.

Recall that if you want to go ahead and return a successful outcome, the convention is to return 0. And actually down here, if you're unsuccessful, what should be perhaps returned instead? AUDIENCE: 1. SPEAKER 1: 1. And again, these are totally arbitrary conventions. You just kind of learn them as you go. But 0 mean success. 1 tends to mean failure. And that now lines up. So now my function main will essentially exit early. So if I go ahead and run make names and then do dot slash names, now if I'm searching for Emma in that array of four names, she's found and only found. Any questions, then, on this here? All right, well, what if I want to do one further thing and combine these two ideas into one final program, namely that of a phone book? So let me go ahead and close these files. Let me go ahead and give myself a new file. I'll call it phonebook.c. And let's actually integrate all of these building blocks as follows, cs50.h again. I'm going to go ahead and include standard io.h.

I'm going to go ahead and include string.h just as before. And now I'm going to do int main void. And now I want to implement the idea of searching a phone book, just like in week 0, but now doing it in C. So let's keep it simple. And we'll have just four names in this phone book, so string names 4 equals. And I'm going to use my same new trick just to save myself some lines of code, Emma, Rodrigo, and then, quote unquote, "Brian," quote unquote, "myself." But then our numbers. So how should we store phone number, would you propose, what data type?

AUDIENCE: [INAUDIBLE] SPEAKER 1: Sorry? AUDIENCE: String. SPEAKER 1: String? Why string? I feel like phone numbers are numbers and strings-- AUDIENCE: Maybe if you store it as a [INAUDIBLE] or an integer, then it's implied that you need to do much [INAUDIBLE].. You don't have [INAUDIBLE] the [INAUDIBLE],, like, [? add ?] [INAUDIBLE] number a dash or something. It would be really hard to manipulate an integer. SPEAKER 1: Exactly. So to summarize if a phone number has dashes in it or parentheses or maybe plus signs abroad, those are characters. Those aren't numbers. So they won't fit in ints or in longs. So even though we call it a phone number, now that you're a programmer, it's not really a number so much as a string that looks like a number. So string is probably the better bet here. And if you consider, too, in certain geographies, you sometimes have to dial 0 to dial someone's number if it's local.

But if it's a 0, it's going to get dropped mathematically because leading zeros don't matter. So again, modeling things that look like numbers but really aren't as integers is probably the wrong call. So let's indeed do string numbers. And I'll give myself four numbers here. And let's do 617 555 how about, 0100. We'll do 617 555 just like in the movies, 0101. Let me fix that. Then we'll do 617 555 [? 0102. ?] And then lastly my number, which shall be-- whoops-- which shall be 617 555 0103.

And I'm doing a same kind of trick, but this is giving me now two arrays, one called names, one called numbers. Here we go, for int i gets 0, i less than 4 i plus plus, so same quick loop as before. I'm going to go ahead and compare now. I'm searching for Emma. And specifically now I'm searching for her number not just her name. So I want to print out her number this time not just found or not found. So as before, I can say if comparing the two strings at names bracket i and, quote unquote, "Emma" equals equals 0, I know that I found Emma. And if I want to go ahead and print out Emma's phone number, what should I do here? It's not names. It's not numbers. What should go between the quotes? AUDIENCE: [INAUDIBLE]. SPEAKER 1: Yeah, so [? %s, ?] remember, just our familiar place holder for strings. And then here not names because I know I'm looking for Emma. Here I want to go ahead and put number. So it's a separate array, but it's at the same location, bracket 1.

Let me go ahead and save that. And down here, I'm going to go ahead and say printf not found, if we don't find Emma, even though we surely will in this case. And I'm going to learn my lesson. I'm going to return 0 for success and return 1 for failure in this case. Let me save the file, scroll my terminal window up a little bit, do make phone book Enter, compiles OK dot slash phone book. And what should I see when I run the program now? AUDIENCE: [INAUDIBLE] SPEAKER 1: 617 555 0100, hopefully.

So this code is correct. And this is an opportunity now for us to criticize it, though, along a different line. This is correct. I've got two arrays, both of size 4, one with names, one with numbers, code finds Emma, prints her number, returns 0. I seem to have done everything correctly. But does anything rub you the wrong way perhaps about the design of this code? Could we do better? Is there's something that's a little arbitrary, a little contrived, a little dangerous about this code?

Any glimpses? Yeah, over here? AUDIENCE: [INAUDIBLE]. SPEAKER 1: Sorry, a little louder. AUDIENCE: [INAUDIBLE] [? two ?] [? single digit ?] [? on both sides ?] [INAUDIBLE]. SPEAKER 1: So we could use a two-dimensional array to store data like this. I would propose it's not strictly necessary, and it might make things a little more complicated, but a reasonable alternative as well. Other thoughts? AUDIENCE: [INAUDIBLE] Emma's number [INAUDIBLE].. SPEAKER 1: Yeah, it's assuming that Emma's number is the first one. And that seems reasonable, right? Emma's name is first. So presumably her number's first. Rodrigo's name is second. So presumably his number is second. And that might be true. But frankly, that's the concern, this sort of honor system that I promised to keep the names in the right order, and I promise to keep the numbers in the right order, when really, that is just sort of an unspoken agreement between me and myself,

or if I'm working with colleagues or classmates, that we all just agree to keep those things in sync. And that's dangerous, right? If you had more numbers than four, you could imagine things very quickly getting slightly out of order. Or god forbid, you sort the names alphabetically, how do you go about sorting the numbers as well and keeping things together? So this feels like an opportunity for one new feature in C and in programming languages more generally, whereby we can actually keep these pieces of data, someone's name and number, together. And today we give ourselves the opportunity to introduce our own custom types. We've seen ints and bools and floats and longs and strings. And string, recall, is a custom CS50 data type. And we'll take that one away in a couple of weeks as a training wheel. But today let's give ourselves our own data type as follows. Typedef is our new keyword today. And it literally means define a type.

It's going to be a structure. And so struct in C is an actual keyword, and it refers to a container, inside of which you can put multiple other data types. Struct is a container for multiple data types. What do I want to contain? Well, I want to give myself a name for everyone. And I want to give myself a number for everyone, even though it's a string because phone numbers can have dashes and parentheses and so forth. And you know what? The name I'm going to give to this structure is going to be person. It's a simple person. But using this syntax, I can teach my compiler, [INAUDIBLE] in this case, that not only are there ints and floats and chars and bools and so forth and strings, there are also person types now in C. They didn't come with the language. But I'm inventing them now with typedef struct person, inside of which, or encapsulated, so to speak, inside of which is going to be two things, name and number.

So what can I do with this? Well, my code gets a little different but better designed, I would argue. Down in my code now, I'm going to give myself an array of people. There's four of us on the staff. And I want to give myself an array of four people. So I might do literally the same approach I've always done when declaring a data type. What data type do you want? Person. And what should my array be called? Well, I could call it persons. Or frankly, I could just call it people in English. And how many people do I want to represent? Four. So my array is called people. It's a size 4. And each element in that array is going to be a person. So this syntax is not new. This syntax up here is new. But as of today now, persons exist in C. Now, my syntax here does have to change a little bit, but not all that much. Now, if I want to go ahead and fill this array, I can do something like this. Emma will be our 0th person.

But I don't just do something like this because, quote unquote, "Emma" is not a person. Quote unquote "Emma" is a name. And quote unquote "617 555 0100" is a number. So I actually need to be a little more specific. I need to say that people 0 name is Emma. And then people 0 number is whatever Emma's was, which was 617 555 0100 semicolon. And now I can do the same thing again, so people bracket 1 dot name gets Rodrigo. People bracket 1 dot number gets 617 555 0101 semicolon.

People bracket 2 dot name gets Brian. And people bracket 2 dot number gets 617 555-- 555-- 0102. And then lastly-- it's getting tedious quickly. But in an ideal world, we would just ask the human for these inputs. Name will be mine. And then lastly, people bracket 3 dot number equals, quote unquote, "617 555 0103." Whew. So it's a little more to write in this case. And so it might rub you the wrong way in that sense. But notice that we're now kind of encapsulating everything together.

We only have four values, each of which is a person. And each of those persons, inside of them, so to speak, have a name and a number. And everything is intricately related. So even if I sought these things by name, they're going to end up having the same associations between numbers and names. So now the last thing I have to do is change my logic down here. It's not sufficient anymore to compare names bracket i against Emma. What should I compare name against Emma? AUDIENCE: [INAUDIBLE].

SPEAKER 1: Dot name. And then down here, numbers doesn't even-- oh, and this was-- this is people. Numbers doesn't exist either. It's people. But I want to print her number here. So I do dot number. So again, we've add a little bit of complexity by adding typedef and these dot notations. But if I go ahead and make my phone book now, all too many errors. Oh interesting. Array index 4 is past the end of the array, which contains four elements. So I made a stupid mistake here. What did I do?

AUDIENCE: [INAUDIBLE] SPEAKER 1: Yeah. So I just kept incrementing incorrectly. Let me save that, run make phone book, Enter. Now it's good. Dot slash phone book, Enter, and hopefully I will see Emma's number. So it's no more correct than before. But it's arguably better designed/ and we'll come back to this later in the semester. [? As ?] you choose your choice of tracks and start implementing applications for the web or mobile devices or games, it's going to be quite common to encapsulate related information like this so that you keep lots of information together, especially when you use something called a database. Yeah? AUDIENCE: [INAUDIBLE] SPEAKER 1: Is there any shortcut for writing everything I did? Yes, you can actually use curly bracket notation. It gets a little uglier in this case so I'm not going to bother doing it. But, yes, there is a way to do it. However, this is, at the end of the day, realize,

kind of a silly program because I'm writing a program to find Emma in a list of names I already wrote. So it's not dynamic at all. So in an ideal world, we would be using get string or something fancier anyway. Other questions on this? All right. So this is only to say we clearly have the ability, then, in code to implement these ideas, like [? Nizari ?] and Eric implemented more physically, using something like this array of lockers. So where do we go from here? Well, unfortunately, [? Nizari ?] benefited from the fact that the lockers were, of course, already sorted sort of behind her by Brian. But there were some price paid, right? Indeed, even we had to wait a little bit of time for all of those numbers to get sorted in the lockers before we could proceed to execute that algorithm. So a question, then, reasonable to ask is, well, how expensive is it to sort numbers? And should you sort numbers and then search?

Or should you just jump right into searching and not worry about sorting the numbers, especially if one might be more costly than the other? These are going to be ultimately trade-offs. So let's consider them as follows. If now the problem at hand is to provide as input to our problem an unsorted list of numbers, the goal of which is to get a sorted list of numbers back out, how do we go about implementing this? For instance, if the numbers are 7, 2, 1, 6, 3, 4, 50 in that order, that unsorted order, the goal at hand is to get out 1, 2, 3, 4, 6, 7, 50 in sorted order from left to right, smallest to largest. So how can we go about implementing that idea? Well, let me go ahead and see. We have a few stress balls left. And we could perhaps do this a little dramatically maybe with eight volunteers, if you will. OK, that's a plan. OK, so 1, about 2, 3, if we could, OK, 4 in the middle there, 5, 6, 7, and let's see-- and let's see, [INAUDIBLE] can come up here.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent