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

(Romina) #1
}
return(0);
}

Here’s a sample run of the program:


Click here to view code image


How many kids are you taking to the water park? 3
Do you have a discount ticket for the park?
Enter E for Employee Discount, S for Sav-More Discount, and N for No
Discount: S
First let's do it with the variables:
You've got 3 kids...
The Sav-More discount saves you 15% on the $17.50 price
Total ticket cost: $44.63
Now let's do it with the pointers:
You've got 3 kids...
The Sav-More discount saves you 15% on the $17.50 price
Total ticket cost: $44.63

There’s nothing too ground-breaking or complicated in this program. It’s more to get you used to using
pointers, including declaring, setting, and referencing pointers of all kinds. Again, when you use
functions that take and return data, you will find yourself in need of pointers constantly.


The Absolute Minimum
The goal of this chapter was to introduce you to pointer variables. A pointer variable
is nothing more than a variable that holds the location of another variable. You can
refer to the pointed-to variable by its name or by dereferencing the pointer.
Pointers have many uses in C, especially in advanced C programming. As you’ll learn
in the next chapter, arrays are nothing more than pointers in disguise. Because pointers
offer more flexibility than arrays, many C programmers stop using arrays when they
master pointers. Key concepts from this chapter include:


  • Get comfortable with memory addresses because they form the basis of pointer
    usage.

  • Use the & to produce the address of a variable.

  • Use the to define a pointer variable and to dereference a pointer variable. pAge
    and age reference the same memory location, as long as you’ve made pAge point
    to age.

  • Don’t try to make a pointer variable of one data type point to a variable of a
    different data type.

  • Don’t worry about the exact address that C uses for variable storage. If you use &, C
    takes care of the rest.

  • Don’t forget to use * when dereferencing your pointer, or you’ll get the wrong

Free download pdf