This lesson is locked. Login or Subscribe for more access!

Pointers

Duration: 3 mins

What are they? Here's what you need to know

Instructor

Matt Boyle

Share with a friend!

Transcript

Let's talk about pointers.

Pointers can seem really tricky at first, especially if you've not come across them in another language, but they're really useful for managing data efficiency. But they're really useful for managing data efficiently. This is going to be a really short, sharp lesson, but you're going to know everything you need to know about pointers by the end of it.

So first, what is a pointer? It's just a variable that holds a memory address. This is a simple example on the screen here. Here x is an integer. It's 42. The ampersand operator gives us its memory address, which we store in p. If you run this, which I will, you'll see x is 42 and p is some really random number thing. This is a memory address. Pointers let us work with that address directly instead of copying the value.

So why bother with pointers? Let's add a couple of functions to this code.

Okay. So take a look at this code and try and predict what's going to happen here. In increment, we pass x by value. Goal makes a copy, so x doesn't change. But increment with pointer, we pass a pointer to x with the ampersand x syntax. The star operator dereferences it, letting us modify the original value.

So let's run this and see. Interesting. So the output shows 42, then 43. So this is really important for efficiency. Imagine if you had a huge struct with pointers. You avoid copying any of it, and you can directly manipulate it as we've seen here.

So what are the downsides of the pointers? Generally, you can see that we're mutating data here. This increment function here, it's maybe not clear that it's going to change the value of x. So generally, I would consider this to be bad practice. A better idea would be for this function to return x, and then we know that it's going to be a new value.

In most cases, you probably want to pass by value. But if memory is a concern for you, then pointers can be really, really useful. You also have to be a lot more careful with pointers because they can be nil. So you need to make sure you check for those things.