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

Study methods

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

Pointers and Memory

Transcript

[MUSIC PLAYING]

DAVID J. MALAN: All right, this is CS50. And this is week 4 on memory, wherein we reveal a topic that's actually fairly distinct to CS50 nowadays as an introductory course, known as pointers. Indeed, today is the day you can tell your friends that you learned something about pointers and, in turn, how computers work underneath the hood. I will say that this is the kind of topic, this is the kind of lecture where probably won't all sink in the first time around. Think back to that fire hose that we showed in week 0. In fact, all these years later, I still remember where I was on campus when, finally, today's topics finally clicked for me. It was in office hours in Eliot house dining Hall in the back right-hand corner, which is only to say, as you approach this week's material, this week's problem set 4, take comfort in knowing that it is challenging. It's meant to be challenging. But, as we ratchet things up and up and up over the past few weeks,

we will start to plateau in just about a week and then it's smooth sailing there on out even though it might not feel that way initially this week. But, this week, we'll focus all the more, indeed, underneath the hood, how information is represented, like this here photograph of the bowl of stress balls that we have most every week. But recall that any time you have an image like this, it of course, is composed of pixels, and those pixels or dots each have some bits or bytes associated with them that prescribe what color those dots should be, but there's only a finite amount of information in there. So if we enhance, enhance, enhance, you don't actually see the 50 more and more clearly. You only see it larger. And, in fact, at this size, you can actually see the dithering, so to speak, which is this cloudiness that looms over the image. And you can kind of see the outlines of the actual pixels. All of those hard vertical and horizontal edges

are the pixels, the dots that compose that image. So this is actually an example of-- and, in fact, on this last slide here, can you see them even most clearly on the screen as we go and go and go. So how do you go about implementing then or representing something like an image? Well, there's bunches of different file formats out there for images. There's GIF, there's JPEGs, there's PNGs, and there's others as well. But the simplest of them, like a bitmap image, is literally just a map of bits horizontally and vertically conceptually. So, for instance, here is a grid of bits 0's and 1's. And suppose, for instance, that maybe 0 represents black and 1 represents white. Can anyone with their human eyes see what this is a picture of even though it's just 0's and 1's? Can you see it? Yeah. So it is actually a smiley face because if the 0's are black and the 1's are white, this is what's actually latent in that image. It's hard to see at this size, of course.

But if we were to shrink that down and actually use square pixels black and white, it would probably pop out all the more clearly. Of course, it's not that useful to store things with single pixels because you can only represent two states like 0 and 1, like black and white. And so here might be that same image actually zoomed in such that you can see all of those individual pixels. But, when it comes to color, we, of course, need more than a single 0 or a single 1 to represent each of those pixels. We probably need like 24, maybe 3 bytes' worth for some red, some green, and some blue. And recall that that's, in fact, one of the ideas we implement-- we talked about in week 0-- how do you go about representing images, for instance? So, more generally, this is actually kind of an art nowadays, if only for fun, to actually use small dots and compose things on the screen.

And, wonderfully, just before we began today, two of your classmates bravely volunteered. And, in fact, let me invite them to come up and introduce themselves before we reveal what they have made on this canvas here using Post-it notes, square paper as their pixels. SELENA: Hello, my name is Selena. I'm a freshman in Wigglesworth. I'm thinking of studying robotics and possibly in secondary and AFBS. DAVID J. MALAN: Welcome. JEFFREY: Hi, I'm Jeffrey, I'm a freshman in Thayer Hall, and I'm thinking about concentrating in econ and CS. DAVID J. MALAN: All right, welcome, and allow me-- hang on to the microphone if you would. I'm going to go ahead and reveal what they kindly did on very, very short notice before class began. And here is what they came up with, a grid of pixels, two colors here. What is it that we're looking at? SELENA: Can you tell what it is? Shall we say-- DAVID J. MALAN: Actually, well, we can ask the audience. What is it they made?

Because they're a little insecure about their pixel art. A ladder? Again. A flamingo. Is it a flamingo? SELENA: No. DAVID J. MALAN: No? SELENA: No, they said a palm tree on an island. DAVID J. MALAN: Oh, it's a palm tree on an island. All right, maybe a round of applause for palm tree on an island, if we could. Thank you. [APPLAUSE] Here we go. So suffice it to say, when you do have just-- thanks very much. If you have just a single color to use, black or white, and you're using 1-bit art, it's actually kind of hard to paint a picture. But if you do have actually more colors at your disposal and an even bigger grid, can you do more interesting things? And so, in fact, we invited some past students to do exactly this. We shared a Google spreadsheet whereby we use the cells instead of as long default rectangles. We just turn them all artificially into squares so that you can use the paint bucket tool and just paint different pixels onto the screen.

And among the pieces of art that some of your predecessors came up with were this here, a scene from Mario using a grid of multicolored pixels, this one here of Scratch the Cat, this one here in honor of the Harvard-Yale football game coming up in a few weeks' time, this one here using a bit of the same. And, in fact, if you'd like to play along at home just for fun, if you go to CS50.ly/art, you can make a copy in your own Google account of that blank spreadsheet and just play around if you'd like to experiment as well. But this is really meant to motivate one of today's topics, which is indeed how we can start to manipulate data at a lower level, including images and other things. And images, of course, can be, among other ways, be represented with RGB, some amount of red, some amount of green, some amount of blue. Before we dive into that, though, let me augment our vocabulary a bit today by adding another base to our system.

So we have binary, of course, which is base 2. We have decimal of course, which is base 10. Today we're going to introduce one more, which is useful in today's concepts as well as others as we'll see down the line known as hexadecimal, where you actually have 16 digits at your disposal. And if any of you are artistically inclined or you might've dabbled in web development, you might actually be familiar with hexadecimal notation itself already. Here, for instance, is a screenshot from Photoshop whereby if you use the so-called color picker to manually choose a color that you want to paint onto the screen, you see a lot of information over here. But salient to today's conversation is this here where there's a hash sign and then typically six or sometimes three digits, in this case. 000000 means that the color I'm going to get here is actually black. So it's sort of no red, no green, no blue, hence the 0's, means you're going to get black.

Meanwhile, if I play around with the same color picker and I instead do FFFFFF, either all caps or in lowercase, I actually get a color that we're going to see today is going to be white, which is like a lot of red, a lot of green, a lot of blue, all the frequencies of light coming together to give us what we know as white light. But now we can play with this because it's no coincidence that these are indeed six digits of sorts, even though they're letters of an alphabet and not numbers yet per se. For instance, FF0000 would seem to mean a lot of red and no green, no blue. And, indeed, that's why we get red according to Photoshop itself. 00F00 gives no red, a lot of green, no blue. And, of course, that's the color Photoshop would give us. And, lastly, 0000FF gives us indeed blue because that's no red, no green, but a lot of blue. So the 0's would seem to make intuitive sense here, if you have no red, no green, no blue.

But what's with the FF? Like FF, of course, in English, are letters of an alphabet, not numbers. Well, it turns out that Photoshop and people in the world of images and people in the world of computer memory tend to use a different system altogether. They don't use binary, and no one, really, in practice uses binary except the computers we use because you can't do or see much with 0's and 1's alone. We humans in the real world use the decimal system, again, 0 through 9, which is just very conventional. But, in the context of computers and specifically memory and files and images, we tend to use hexadecimal, which gives us another six digits in our vocabulary, and I'm deliberately calling them digits, even though they appear to be letters. But this is just a convention. We just need we need-- we want six more symbols. So we have 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, I don't want to say 10,

and I don't want to write 10 because that would be two symbols on the screen. So the world, years ago, decided, all right, when we want to represent 10 with a single digit, let's call it A and then B for 11, and then C and then D and then E, and then F, where F happens to be 15. So this is what's known as hexadecimal notation. And this really is the last of the notations or systems that we'll use. You can use uppercase or lowercase. The software you use decides what convention to use, but they mean one and the same. So hexadecimal, hex implying 16 in this case, otherwise known as base 16. All right, so just a bit of jargon out of the way, how does it actually work mathematically? The exact same way as in week 0. The math is a little different. It's not going to come to intuitively in the same way, but the system is the same. If you've got two-digit values here, like here are some placeholders, the columns represent the 16th to the 0-th place, the 16th to the 1 place.

That math is easy. This is the 1's place. This is the 16's place instead of in our human decimal world 1's, 10's, 100's, or, in the binary world, 1, 2, 4, 8, same idea, just different powers for each of the columns. All right, so this number 00 represents the number you and I know as 0. In hexadecimal, 01 represents the number you and I know is 1. And it goes from there pretty straightforwardly. 05, 06, 07, 08, 09 translates to exactly what we in decimal the number 9

because it's 1 times 9 plus 16 times 0. Gets a little more interesting when you're using two digits, but you're using hexadecimal because now if I want to count as high as 10 in decimal, I would represent that in hexadecimal as 0A. 0B is 11. 0C, 0D, 0E, 0F, and there's our F. And F I'll stipulate just represents the number we know as 15. So 1 times F gives us 15, plus 16 times 0. All right, dot dot dot, we're not going to do the whole range of numbers here.

But I don't want to call this 10 in hexadecimal just like in binary. Even though you might see 10, you don't say 10. You would say 10, same in hexadecimal. So this is 10. But if I translate this pair of digits to decimal, what does this represent? So this is 16 because I've got 16 times 1 plus 1 times 0 and on up and on up and on up. We can do this for quite a while. It gets interesting only once we get to the end. Using hexadecimal, as I've defined it, what's the highest we can count with two digits then in hexadecimal? FF would be the highest because F seems to be the largest digit. So this is actually 16 times 15 plus 1 times 15 actually gives me 255. So that is as high as I can count in hexadecimal from 00 to FF, otherwise known as 0 to 255. And if you don't believe me, a quick little math will give us that, again, 16 times 15 plus 1 times 15 as well. All right, so how is this useful doing out this math?

Well, we have the following-- oh, actually, why is this useful? So it's very common to use two digits of hex, maybe possibly more. Why? Well, it turns out that to represent the numbers 0 through 15-- let me spread these apart now just to be deliberate about it, 0 through 15. How many bits do you need? Well, 0, you can use any number of bits. How about 15? How many bits-- Sorry, how many bits do you need to count to 15? So it turns out that's four because, in binary, that would be,

what, the 8's place plus the 4's place plus the 2's place, plus the 1, which I think gives me indeed 15. So why is hexadecimal useful? Well, it turns out that you can represent a single hex digit, whether it's 0 or F, using four bits, no matter what. And so why do we tend to use two hexadecimal digits? Well, it's just useful to be able to describe a single byte, otherwise known as eight bits, using two digits instead of eight. So, in binary, we'd have to use eight.

In hexadecimal we can just use two, and it's just useful visually. Hexadecimal is useful as a result. All right, so when are we going to see this? And why are we going to see hexadecimal? Well, here's a grid of the computer's memory just abstracted away as some byte, byte, byte, byte in rows and columns. Well, here is how we might number those bytes. As I've stipulated for several weeks now, we could call this byte 0, this byte 1, byte 2, dot dot dot all the way to byte 15. But, by convention, we don't use decimal, and we definitely don't use binary. Instead, a computer scientist would think of the addresses, the locations of, the count of bytes in memory as still starting from 0, 1, 2, 3 on up. But, as soon as you get to 8, 9, A, B, C, D, E, F. Again, just a convention. There's nothing really intellectually interesting here other than we're using a different base system instead. Here's how the others might play out.

And it gets a little confusing because this 10 is not 10 if it's in hexadecimal. But, clearly, there's some potential ambiguities here. It's pretty obvious now that if you see an A through F, OK, it's probably hexadecimal. But if you see 10 or 11 or 12, well, it's maybe not-- it might not be 10 or 11 or 12. Those might be hexadecimal even though 1A, 1B is. So this is an ambiguity. And so what we're also going to see today that the way humans have mitigated this potential ambiguity is, when you write things in hexadecimal, by convention, you put 0x before them, a 0 and typically a lowercase x. That does not mean anything mathematically. It's not an extra 0 per se. It just means, to the human reading this, here comes a hexadecimal number. And now there is no ambiguity. So we're going to see a lot of this today. Generally, we won't care about the numbers, but that is what we're going to be looking at is hexadecimal.

So any questions on hexadecimal which, again, is just another way of representing numbers? Any questions on hexadecimal? OK, so let's see this in practice and start to tease apart what's going on underneath the hood of our computer all of this time when we actually start to use variables and more. So here's a single line of code. Give me an integer called n, and initialize it to the value of 50, so fairly straightforward. So let's actually do something with this kind of code. Let me go into VS Code here. Let me go ahead and create a program called--

let's call it addresses.c because I want to look at the locations in memory, the address of things in memory. And let me stipulate to, as we've said in the past, just as mailboxes in the real world, houses and buildings in the real world have unique addresses, like we are at 45 Quincy Street, Cambridge, Massachusetts 02138, USA. Similarly does your computer's memory have addresses. But they're super simple numbers like 0, 1, 2 dot dot dot all the way on up. So I've created a program now called addresses.c. Let's just play around with some familiar code. Let me include stdio.h. Let me do int main(void), so no command line arguments for this. Let me declare that variable n, set it equal to 50. And let's just print out n. So this is like week 1 stuff, super simple and presumably familiar by now whereby I want to print out using the %i placeholder the value there of n. All right, hopefully, if no syntax errors, I can do make addresses, enter,

so far, so good. ./addresses enter. And I see, as expected, the number 50. But what's actually going on inside of the computer's memory in this case? Well, we can actually see that over here. Let's look at this grid of memory here. For today's purposes, I don't necessarily know where in the computer's memory at this point. The n is going to end up-- so let's just arbitrarily say the computer finds room for the int in the bottom right-hand corner of my screen. The size of it is deliberate because, recall, that integers tend to be how many bytes on most systems nowadays? 4 bytes by convention, aka 32 bits if you multiply by 8. So who knows? n might very well end up in the bottom right-hand corner of my screen here, with the number 50 stored there. Now, it's not literally the number 50. There's literally 32 0's and 1's in the computer's memory that are turned on and off to represent the pattern that gives me the decimal number 50.

So, again, that's sort of week 1-style stuff. But what we're thinking about now is the computer's memory. In fact, even though we refer to it as n in my code, it's got to live somewhere. And the address at which it might live for the sake of discussion is maybe something notationally written in hexadecimal like 0x123, completely arbitrary. In practice, it's probably a bigger number than that, but, for the sake of discussion, let's assume that that 50, the variable n, just so happened to get placed by the computer at location 0x123. Can we see that in code? We haven't yet thus far. But if I propose here, maybe going back into VS Code in a moment, maybe we can actually use some slightly new syntax and poke around the contents of the computer's memory. But, before we do that, we do need a few new building blocks. And there's not much new syntax today, but we're going to go pretty darn far in terms of capabilities with just a few new symbols.

It turns out that, in C, if you use the ampersand operator, just one of them, not two. Two means and logically, just like two vertical bars meant or. If you use just one of them, as we are going to today, that is going to be the so-called address of operator. So you can write ampersand and the name of a variable, and the compiler essentially will tell you where that variable is in the computer's memory. Or, more technically, when the program is running, you will be told where it is. The star operator or a single asterisk is not multiply in this context. It's going to be the dereference operator, which is going to be a trick via which we can have an address and go there, sort of following a breadcrumb, following X marks the spot on a map and going to that location in memory and just see what's there. Is it an int? Is it a char? Is it a string or something else? So these sort of reverse the effects of each other. This tells you the address of something.

This tells you how to get to something. So the address of operator and the dereference operator, so to speak. But we need one other building block. And this one's going to be useful in the context of printf. Recall that printf has all those format codes like %s for string, %i for integer, %f for float. Turns out there's another one, %p, which is going to allow us to print what are called pointers, which are really, for now, synonymous with addresses in memory. So using just those new building blocks, let me propose that we do the following. Leveraging this notion of a pointer. I'm going to change my code in just a moment to still have the same single line here int n equals 50. But then let's create a second variable called p, just for convenience. But let's declare it as a pointer. A pointer is simply a variable that stores the address of something. So it's a variable that stores the address of something like 0x123 or some such value.

How do you use it syntactically? It's a little weird, especially since we've used star and the ampersand in other ways already. But you say that I want a variable called p. The type of this variable is going to be a pointer, so to speak. How do express that? Well, I want it to be the address of an integer. So you say int, but you make clear that it's the address of an integer, not an actual integer per se, by putting a star here. Of all the things we have and will see in C, I will concede this is the most confusing way to do this. Ideally, there would just be a variable called pointer, and you just write it, and you get a variable that's a pointer. But, in the case of C, you actually specify that this variable p will indeed be an address that points to an integer. So you just have to let that ingrain in yourself. This one's a little easier. &n, how would you express that in English based on my previous definition?

The address of n, &n just means get the address of n. And because code recall is generally read and executed right to left, in this case, this says wherever n is, get the address of it like 0x123 and assign it to the variable p. What is the variable p? It is a pointer, so to speak, that is, the address of an integer. So it's a little-- it is arcane. It's a little weird. But this is kind of as low-level as we can get with C with just telling the computer exactly what we want to do. So let's see this. Let me go back to VS Code here. And, quite simply, after clearing my terminal, let me go ahead and print out, using %p, the following address of n. And then we'll enhance this code to actually-- actually, no, let's do this exactly as I did. Let's go back into VS Code here. Let's declare int *p equals &p and then print out not i itself-- not n itself, but print out using %p the value of p itself. So what is this going to do for me? It should print out the address of n.

All right, so, in my terminal window, make addresses, enter. Huh, I messed up because I did something stupid. I forgot the semicolon as you might have one or more times the past few weeks. Let's do this again. Let's make addresses. Enter. Dammit! I screwed up a second time. I want the address of n, not the address of p. All right, so I'm doing well. So, so much for remembering this concept from the dining hall of Eliot House. All right, so make addresses. Enter, oh, my god, thank you.

All right, so now it works, hopefully. ./addresses, it's not going to be as simple in the actual computer as 0x123. It's probably going to be a bigger number. And, indeed, it's a much bigger number, but there is an address of some sort. Might be different run on a different system, but it turns out that the variable n is stored at location 0x7ffef3c2925c, which is just a really big number that if we did all of the math on paper, pencil or computer would be a really big decimal number. Why?

The server has lots of gigabytes of memory, billions of bytes. So, of course, it's probably going to be a big number like that. Now I don't strictly have to create p. And, in fact, let me do what my instinct had me doing a moment ago. Let me delete p and simply just print out directly, what is the address of n? Let me go ahead and recompile the code. Make addresses, ./addresses, and I actually do get a different address this time. Why? Because I've run the program again and things got organized in memory a little bit differently. So these numbers are not going to remain invariant, unchanged. But, every time you run the program, things might deliberately, or for other reasons, get moved around. But all I have done is asked the computer explicitly, what is the address of n? And that's what I'm seeing. All right, so, just to recap then what these lines of code are doing, previously, when I had both n and p, this latter line

is just asking what's the address of n storing the address thereof in this variable p. But there's some disagreement in the world as to how you should write this syntactically. And just so you've seen it in case you see a video or a tutorial or a book that disagrees, this is really the conventional way to write the star. That means, hey, computer, this is a pointer to an integer, the address of an integer. You could also write it this way. And some people do this. I do think it's a little-- this can get you into trouble in certain cases. Some people do this with spaces on either side, which even looks more like multiplication, but it's not. All three will work, but the recommended conventional way is indeed to do this, even though I do concede it looks a little weird, but you'll get more and more comfortable over time. All right, so if you're with me that what we've just done amounts to just figuring out where in the computer's memory

a variable actually lives, I think we can poke around further to see even more of what's going on. In fact, let me go ahead and propose this. Let me propose here that we go back to VS Code here, clear my terminal window, and let's go back to the version before where I explicitly did have p. So int *p equals &n. And then, again, printf, quote, unquote, and what I had before was %p backslash n comma p. So this printed again, the exact same thing the address of n.

But what if I actually want to print out n itself just like I did in week 0? Well, in week 0-- sorry, just like I did in week 1. In week 1, I could have just done, as I did a few minutes ago, this. And this would print out in the old-school way the value of n and just as a quick check, make addresses, ./addresses. And there's my 50 as expected. But, now that I have these two other operators whereby I have both ampersand and star, I can poke around with them, play around with them in ways that should, hopefully, with some practice, make sense. So, for instance, I could do this again int *p equals the address of n. Well, I could print out n literally as I'm doing now. Or I could use the location of n called p and go there with the second of these two operators, the dereference operator. The dereference operator, the single star, means go to this address. And so now, when I go back to VS Code and I do make addresses, ./addresses, enter, I still get 50.

I'm kind of jumping through hoops proverbially here because this is the stupid, longer, more complicated way to print out the value of 50, but it just speaks to the relative power that I have by just figuring out what the address is and then going there. But the confusing part I do think about this for me and for most folks learning this is the following-- the designers of C, decades ago, made, I would say, the unfortunate decision to use the star in two different ways-- in three different ways in total-- one, multiplication. We saw that in week 1 since. But notice that there's two different uses of this star operator. Here, it literally means go there, dereference the address, that is, follow the breadcrumbs, and go there. But, when you declare the pointer, when you create the pointer, you also use a star, but you also use the type. So what's confusing, at least to me, is that we're

using the star in two different ways, both of which are related to addresses, both of which are related to pointers. But, when you create a variable or declare a variable for the first time, you specify not only star, but the type of the pointer, just like any other variable declaration. But, when you use the pointer subsequently, you do not mention the data type. Again, the compiler is smart enough to remember. OK, got it. You wanted a pointer to an integer. The compiler will remember that for you. You do not need to remind it. So admittedly confusing, but, on line 6, we are declaring the pointer and assigning it a value. And, on line 7, we are dereferencing the pointer. So one creates the pointer, one goes to that there address. So, in terms of what's going on inside of the computer's memory, let me propose that if we revisit the same grid, and we propose that 50 ended up down here. The value n is actually technically at 0x123.

What exactly is p, the second variable? Well, I could draw it as follows in my memory. Maybe, by chance, it ends up here sort of higher up on my slide. But this is the variable called p. And the value of p is simply literally the address of n. Why is p so big? Well, it turns out, on most systems nowadays, pointers, that is, addresses, are 64 bits, or 8 bytes. So they just use a lot of bits. Why? Well, you and I have gigabytes, again, of memory nowadays, and if you're counting up to the billions of bytes, you actually need more than 4 bytes, or 32 bits, because recall, from week 0 even, the highest you can count with 4 bytes or 32 bits is 4 billion. But some of you probably have Macs or PCs that have 5 gigabytes, 6 gigabytes, 8 gigabytes or more of memory nowadays. That means we need 64 bits to count that high, so we can actually label every memory location in order to access these spots. So what is p?

It's just a variable whose value happens to be an address. What is n? Well, it simply happens to be an integer at that address. What questions do you have on this? Yeah. Are you able to use more than one pointer in main? Absolutely, just like variables, you can create as many as you want, including arrays thereof. How do you differentiate them? By way of their name. So I'm using p because it sounds like pointer, but I could call it q or r or s or t or use an actual English word to describe my variable. I'm just using p for short, just like any variable. Yeah. AUDIENCE: Does a pointer not have an address itself? DAVID J. MALAN: Oh, good question. Does the pointer have an address itself? Short answer, yes, because anything in your computer's memory has an address. And odds are it really has 8 addresses associated with it. So maybe we refer to it by the first one or something like that.

There actually exists-- but we won't do this today-- pointers to pointers, which answers that question. But here I'm leaving it abstracted away and just calling it p. But it absolutely has an address. Other questions? Yeah. AUDIENCE: You may have already said this, but when we're referencing things in the code [INAUDIBLE]? DAVID J. MALAN: A good question. When you're referencing p in your code, do you dereference it? Do you use *p? Short answer, yes, if you want to go to that location. And that is usually, as we'll see this week and next week, how pointers are useful. You want to go to that location and do something there. It is rarely, if ever, helpful to literally print or see the actual address because who really cares? Especially if it changes every time I run my code.

We, as programmers, don't care where things are but that we can get to those locations. A good question. Yeah. Sorry. AUDIENCE: [INAUDIBLE] physical memory [INAUDIBLE]? DAVID J. MALAN: Yes, without going down this rabbit hole today, we're talking really about virtual memory. This maps underneath the hood using virtual memory to physical memory. But, for all intents and purposes, we're talking about one and the same today, old computers, simpler computers, simpler times. OK, so how can we now think about this? Well, that is literally what's going on in the computer's memory.

But, as I just said, rarely do we actually care that it's specifically at 0x123. And, in fact, the name pointer kind of conjures up a nice metaphor here. Let's ignore all of the bytes of memory that we're not even using or talking about, anyway. And who really cares about 0x123? Let's just abstract that away, as we've done in the past with literally an arrow when drawing or talking about these things, and just think of p as being a variable that literally points to another location in memory. So, indeed, whenever a computer scientist is talking about or arguing about or designing something that involves memory, they're not going to get into the weeds of doing 0x anything. They're just going to use arrows to draw things on paper or digitally. And, in fact, next week, when these sort of all comes to a head, when it comes to memory, we're going to build things in computer's memory, known as data structures, fancier structures than simply arrays.

We're going to do one-dimensional structures, two-dimensional structures, and we're going to use pointers as sort of a thread with needle to connect this location with this one with this one and this one and start to create two-dimensional objects, if you will, inside of our Macs or PCs, our phone's memory as well. So, to make this super clear, we actually do have a nice metaphor. Maybe if you wouldn't mind coming up, I keep saying that can think of addresses in memory as being akin to physical addresses in the real world, like mailboxes for, say, this building, again, 45 Quincy Street in Cambridge, Massachusetts. And here, then, is a mailbox that has the name p. So this is appropriate because if a pointer is a variable that stores an address, this here mailbox called p would seem to be, I'll say, storing an address. Meanwhile, Yulia has a separate mailbox here that's actually called n. So it's like a variable in memory.

We're kind of cheating because, technically, the pointer would be twice as big as this mailbox. But Home Depot only has so many different sizes, so they look the same physically. But n, according to this story, lives at address 0x123. So if I am the computer and I am executing code that looks like *p, go to the address stored in p. That's akin to a person opening up a mailbox, looking inside, seeing that what's in there is not an actual value you care about per se, but it's kind of like a treasure map, X marks the spot, if we sort of abuse the metaphor, which just means if I want to go to the address in p, that means I look in computer's memory. And, just to be dramatic, we can do this too. We've got a little big foam finger. This is like the computer pointing at the actual location 0x123, and, voila, there is the number 50 that we care about. And, for those following along at home, maybe avert your eyes here in Sanders,

we can similarly do this with the Yale foam finger as well to dereference that as well. And the crowd went wild for those of you watching from New Haven today with applause. So thank you to the Yulia, though, for this particular demo. Yes, yes, we will enhance the applause in the final version of the video. So let's now revisit, admittedly, a bit of a white lie that we've been telling for a few weeks now. And I kind of tripped over this in week one but then sort of waved my hand

and solved it real quickly by introducing the CS50 library. But I'm going to propose that we revisit what a string actually is. Now, we use strings in week 1. We then began, in week 2, to talk about strings, thank you, as just being an array of characters, so that was the first reveal. But, even then, we kept using the word string. But it turns out that strings do not exist in C as a data type. Strings are not a CS50 thing per se, but there is literally no keyword in C called S-T-R-I-N-G, string. It's a concept that exists in C, so nothing is that we've said over the past few weeks has anything to do with CS50, per se. Almost every programming language you'll encounter in the real world supports strings in some way, but my claim today is that the keyword string is actually made up for us for convenience over the past few weeks. Now, why is that? Well, up until now, we have been creating strings in code with lines like this.

String s equals, quote, unquote, "HI!" in all caps, semicolon. What that would do, according to week 2's discussion of memory, is it would give us four bytes in memory for HI Exclamation point and a fourth byte, to be clear, for the null character, N-U-L-L, the backslash 0, which is just 8 0 bytes. And, therefore, were able to manipulate that string as though it were an array. So S bracket 0 is the first character. S bracket 3 is the very last character, specifically that null character. Well, really, we can start to think about strings a little differently still today. In fact, let me go back over to VS Code here, clear my terminal window, and let's stop playing around with integers like number 50. And, instead, let's do this. Let's give myself a string s equals, quote, unquote, "HI!" And then let's go ahead and print it out, just like in week 1, with %s backslash n comma s. Let me go ahead and increase the size of my terminal window. Do make addresses.

And here is the very same mistake we glossed over in week 1. Error, use of undeclared identifier string. Did you mean stdin? Now, maybe that does sound familiar, but it's kind of a red herring. This has nothing to do with stdin per se. String is undeclared because it doesn't exist in C by default. And, in fact, it thinks maybe this is a typo. stdin in is a thing that exists in programming languages, but string, I said, in C, does not. But this fix for me, recall in week 1, was to very quickly

say, oh, we'll come back to that. And, at the top of my code, I went in and added one more include, cs50.h And, somehow, if I clear my terminal, rerun make addresses, that solved everything, and string was brought into existence. But how exactly was that the case? Well, we'll see today what's actually going on underneath that hood as well. So what have I just done with this code? I've simply printed out the string s. But, notice, I claim, what's really going on if I visit the actual memory in the computer is, yeah, it's an array. But if an array is just a chunk of contiguous memory, certainly, we could figure out what the bytes are, the addresses are of each of those characters H-I exclamation point, and the null character. And, again, for the sake of simple discussion, suppose the H is at 0x123, stands to reason that I is going to be at 0x124, exclamation points at 0x125, and the null character's at 0x126. The specific numbers don't matter, but what

does matter is that they are 1 byte apart, and that is literally what I've meant all these weeks when I say contiguous. Back to back to back, they're literally 1 byte apart. So, once we know this, can we leverage this to play around with and see strings, perhaps, in a somewhat different light? Well, let me go ahead and do this. Let me go back to VS Code here after clearing my terminal. Let's leave string s as is, but let's print out a few different things. Let's actually print out what is inside of s. %p backslash n is how I can display an address, aka pointer. And let's print out the value of s. Let me go down to my terminal and do make addresses, enter. ./addresses. And what I see now is a seemingly random but a much bigger hexadecimal address. So it seems that s is not a string, per se, because I literally just told the computer to print it out with printf, albeit using %p instead of s. But %p just means show me the address of a variable.

And it seems that s's technical value is 0X59FB1699D004. Now, that is the longer version of what I just proposed, for discussion's sake, is 0x123. Well, let's be a little more pedantic here. Let me go ahead and print a couple of more things. Let me print out another address using %p, but let me print out the address of the first character in s using my array notation. And then let me do some quick copy-paste just to see a few more of these.

Let me print out location 1, location 2, and location 3. So we're really kind of making use of this arcane-looking syntax today, lots of %p's, but that just means show me, address, address, address, address, and so forth. s[0] is from week 2-- just show me, using array notation, the first character, the second character, the third, and the fourth. And & is new today. It juts means show me the address of that character, not the actual character. So if I go back down to my terminal window, make addresses again, I'm going to see five values in total now, ./addresses gives me this. Let me zoom in, and what's noteworthy is that the very first one is identical to the second one, which seems to imply that s has the same address as the first character of s, but that sort of makes logical sense because what else would it be if not the first one. And so what we're seeing here now is a hint that,

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent