C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

24. Solving the Mystery of Pointers


In This Chapter


  • Working with memory addresses

  • Defining pointer variables

  • Using the dereferencing *


Pointer variables, often called pointers, let you do much more with C than you can with
programming languages that don’t support pointers. When you first learn about pointers, you’ll
probably ask, “What’s the point?” (Even after you master them, you might ask the same thing!)
Pointers provide the means for the true power of C programming. This book exposes the tip of the
pointer iceberg. The concepts you learn here will form the foundation of your C programming future.


Memory Addresses


Inside your computer is a bunch of memory. The memory holds your program as it executes, and it
also holds your program’s variables. Just as every house has a different address, every memory
location has a different address. Not coincidentally, the memory locations have their own addresses
as well. As with house addresses, the memory addresses are all unique; no two are the same. Your
memory acts a little like one big hardware array, with each address being a different subscript and
each memory location being a different array element.


When you define variables, C finds an unused place in memory and attaches a name to that memory
location. That’s a good thing. Instead of having to remember that an order number is stored at memory
address 34532, you only have to remember the name orderNum (assuming that you named the
variable orderNum when you defined the variable). The name orderNum is much easier to
remember than a number.


Defining Pointer Variables


As with any other type of variable, you must define a pointer variable before you can use it. Before
going further, you need to learn two new operators. Table 24.1 shows them, along with their
descriptions.


TABLE 24.1 The Pointer Operators

You’ve seen the * before. How does C know the difference between multiplication and
dereferencing? The context of how you use them determines how C interprets them. You’ve also seen
the & before scanf() variables. The & in scanf() is the address-of operator. scanf() requires
that you send it the address of non-array variables.


The following shows how you would define an integer and a floating-point variable:

Free download pdf