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

(Romina) #1
int num;
float value;

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


Click here to view code image


int * pNum; /* Defines two pointer variables */
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.


Click here to view code image


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 24.1 shows what the resulting memory looks like.

Free download pdf