Understanding Pointers 201
9
Pointers and Variable Types ................................................................................
The previous discussion ignores the fact that different variable types occupy different
amounts of memory. For the more common PC operating systems, an shorttakes two
bytes, a floattakes four bytes, and so on. Each individual byte of memory has its own
address, so a multibyte variable actually occupies several addresses.
How, then, do pointers handle the addresses of multibyte variables? Here’s how it works:
The address of a variable is actually the address of the first (lowest) byte it occupies.
This can be illustrated with an example that declares and initializes three variables:
short vshort = 12252;
char vchar = 90;
float vfloat = 1200.156004;
These variables are stored in memory as shown in Figure 9.5. In this figure, the short
variable occupies two bytes, the charvariable occupies one byte, and the floatvariable
occupies four bytes.
FIGURE9.5
Different types of
numeric variables
occupy different
amounts of storage
space in memory.
vint vchar vfloat
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
12252 90 1200.156004
Now declare and initialize pointers to these three variables:
int *p_vshort;
char *p_vchar;
float *p_vfloat;
/* additional code goes here */
p_vshort = &vshort;
p_vchar = &vchar;
p_vfloat = &vfloat;
Each pointer is equal to the address of the first byte of the pointed-to variable. Thus,
p_vshortequals 1000 ,p_vcharequals 1003 , andp_vfloatequals 1006. Remember,
however, that each pointer was declared to point to a certain type of variable. The com-
piler knows that a pointer to type shortpoints to the first of two bytes, a pointer to type
floatpoints to the first of four bytes, and so on. This is illustrated in Figure 9.6.
15 448201x-CH09 8/13/02 11:21 AM Page 201