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

(Romina) #1

(and confuse more people). Dereferencing just means that you use the pointer to get to the other
variable. When you dereference, use the * dereferencing operator.


In a nutshell, here are two ways to change the value of age (assuming that the variables are defined
as described earlier):


age = 25;

and


Click here to view code image


*pAge = 25; /* Stores 25 where pAge points */

This assignment tells C to store the value 25 at the address pointed to by pAge. Because pAge
points to the memory location holding the variable age, 25 is stored in age.


Notice that you can use a variable name to store a value or dereference a pointer that points to the
variable. You also can use a variable’s value in the same way. Here are two ways to print the
contents of age:


Click here to view code image


printf("The age is %d.\n", age);

and


Click here to view code image


printf("The age is %d.\n", *pAge);

The dereferencing operator is used when a function works with a pointer variable that it is sent. In
Chapter 32, “Returning Data from Your Functions,” you’ll learn how to pass pointers to functions.
When a function uses a pointer variable that is sent from another function, you must use the
dereferencing operator before the variable name everywhere it appears.


The true power of pointers comes in the chapters that discuss functions, but getting you used to
pointers still makes sense. Here’s a simple program that declares integer, float, and character
variables, as well as pointer versions of all three:


Click here to view code image


// Example program #1 from Chapter 24 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter24ex1.c
/* This program demonstrates pointers by declaring and initializing
both regular and pointer variables for int, float, and char types
and then displays the values of each. */
#include <stdio.h>

main()
{
int kids;
int * pKids;
float price;
Free download pdf