iOS Development

Course No. 10-152-139

Chapter 9 — Addresses and Pointers

I hear the term “pointer” all the time, but I don’t really know what it means.

Getting Addresses

  • Here’s a spot in RAM


  • Each square represents a byte.
  • Now lets make a C variable.
  • Here’s what happens in RAM.
  • An int is usually 4 bytes long. In this case the int is 4 bytes that starts in address 1192.


  • Next, we’ll add a pointer to this int. A pointer is an int that has an address of something in its bytes, rather than a value that means something, like count.
  • Now let’s look at an actual address of count
  • 0×7fff5fbff80c?
    • This is in base 16 or hexadecimal format. You will usually hear programmers say this is, “in hex.”

Storing addresses in pointers

  • Without the *, the simple int variable reads as, “an int variable named ‘count’”.
  • The * changes a variable.
    • int *countPointer
      • The variable becomes a pointer to an int. This can be confusing because pointers are themselves int variables. This means that this pointer can only point to an int.
    • float *pricePointer
      • This is a pointer to a float. The pointer itself is an int, but this pointer can only point to a float.
  • Here’s what it looks like.


  • The way we got the value of the address, 1192, was with the &.
    • &count.
      • This reads as, “the address of the count variable”, and returns 1192 in our example.
  • Here’s the whole line again.
  • It reads as, “a pointer to an int named ‘countPointer’ that is assigned the address of the int variable named ‘count’.”
  • An interesting quirk about this is that it doesn’t matter where you put the *. These are all correct and mean the same thing.
  • However, the convention among Objective-C coders is to have it here:

Getting the data at an address

  • We can use the * in two ways:
    • When we declare a pointer variable.
    • When we want to see the value stored at the pointer.
  • Notice line 7:
  • You an also use the * to assign data to the value a pointer is addressing.
  • Look at line 7 here:
  • One more interesting thing. What does this line of code mean?
    • What does this imply about the nature of the word main?

How many bytes?

  • sizeof() is a function we use a lot in C programming. It tells us the actual size of a variable.

NULL

  • NULL is just zero!
  • It is used when you want a pointer to point to nothing.
  • When we make a number variable and want it to point to a safe value we usually assign it zero.
  • For pointers, we use NULL.
  • Since NULL is just zero and zero is also false, this is a common trick in C:

Stylish pointer declarations

  • This can catch a lot of people off guard.
    • They are all floats!
  • What about these?
    • Here, only price is a pointer to a float. The other two are just floats.
  • To fix this we can do:
  • OR this, which is a much better way to code anyway: