C Tutorial (24) : Pointer

Pointer variables, often called pointers, let you do much more with C than you can with programming languages that don’t support pointers.Pointers provide the means for the true power of C programming. 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. 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.

         Pointer operators
     &                   Address-of operator
     *                   Dereferencing-of operator

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:

int num; 
float value;

To define an integer pointer variable and a floating-point pointer variable, you simply insert an *:

/* Defines two pointer variables */
int * pNum;  
float * pValue;

Note : There’s nothing special about the names of pointer variables. Many C programmers like to preface pointer variable names with a p, as done here, but you can name them anything you like. The p simply reminds you they are pointer variables, not regular variables.

All data types have corresponding pointer data types—there are character pointers, long integer pointers, and so on.

Pointer variables hold addresses of other variables. That’s their primary purpose. Use the address-of operator, &, to assign the address of one variable to a pointer. Until you assign an address of a variable to a pointer, the pointer is uninitialized and you can’t use it for anything.

The following code defines an integer variable named age and stores 19 in age. Then a pointer named pAge is defined and initialized to point to age. The address-of operator reads just like it sounds. The second line that follows tells C to put the address of age into pAge.

int age = 19; /* Stores a 19 in age */ 
int * pAge = &age; /* Links up the pointer */

You have no idea exactly what address C will store age at. However, whatever address C uses, pAge will hold that address. When a pointer variable holds the address of another variable, it essentially points to that variable. Assuming that age is stored at the address 18826 (only C knows exactly where it is stored), Figure shows what the resulting memory looks like.

c_pointer

The variable pAge points to age if pAge holds the address of age.

Note : Just because you define two variables back to back doesn’t mean that C stores them back to back in memory. C might store them together, but it also might not.

Warning : Never try to set the address of one type of variable to a pointer variable of a different type. C lets you assign the address of one type of variable only to a pointer defined with the same data type.

The * isn’t part of a pointer variable’s name. You use the * dereferencing operator for several things, but in the pointer definition, the * exists only to tell C that the variable is a pointer, not a regular variable.

Using the Dereferencing *

As soon as you link up a pointer to another variable, you can work with the other value by dereferencing the pointer. 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:

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

This assignment tells C to store the value 25 at the address pointed to by pAge.

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:

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

The dereferencing operator is used when a function works with a pointer variable that it is sent. 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.

Here’s a simple program that declares integer, float, and character variables, as well as pointer versions of all three:

/* 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;
float * pPrice; 

char code;
char * pCode;

price = 17.50; 
pPrice = &price;

printf("\nHow many kids are you taking to the water park? "); 
scanf(" %d", &kids);

pKids = &kids;
printf("\nDo you have a discount ticket for the park?"); 
printf("\nEnter E for Employee Discount, S for Sav-More "); 
printf("Discount, or N for No Discount: ");

scanf(" %c", &code);   /* scanf(" %c", pcode) : Try this also */  

pCode = &code;
printf("\nFirst let's do it with the variables:\n"); 
printf("You've got %d kids...\n", kids);

switch (code) 
{ 
case ('E') :
  printf("The employee discount saves you 25%% on the "); 
  printf("$%.2f price", price);
  printf("\nTotal ticket cost: $%.2f", (price*.75*kids)); 
  break;
case ('S') :
  printf("The Sav-more discount saves you 15%% on the "); 
  printf("$%.2f price", price);
  printf("\nTotal ticket cost: $%.2f", (price*.85*kids)); 
  break;
default : 
  // Either entered N for No Discount or 
  // an invalid letter
  printf("You will be paying full price of "); 
  printf("$%.2f for your tickets", price);
}

// Now repeat the same code, but use dereferenced pointers and get 
// the same results

printf("\n\n\nNow let's do it with the pointers:\n"); 
printf("You've got %d kids...\n", *pKids);

switch (*pCode) 
{ 
case ('E') :
printf("The employee discount saves you 25%% on the "); 
printf("$%.2f price", *pPrice);
printf("\nTotal ticket cost: $%.2f", (*pPrice * .75 * *pKids));
break;

case ('S') :
printf("The Sav-more discount saves you 15%% on the "); 
printf("$%.2f price", *pPrice);
printf("\nTotal ticket cost $%.2f", (*pPrice * .85 * *pKids));
break;

default : 
// Either entered N for No Discount or an invalid letter
printf("You will be paying full price of "); 
printf("$%.2f for your tickets", *pPrice);
}

return(0);
}

Here’s a sample run of the program:

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

At this point (pun not intended!), pointers will not seem to help at all. The only thing you might feel a little better about is knowing what the & inside scanf() really means.

 

Sorting < Prev                                                                                    Next > Array & Pointer

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s