Programming in C

(Barry) #1
Pointers and Memory Addresses 275

memory to hold the value of countwhile the program is executing.This location might
be at address 500, for example, inside the computer’s memory.
Luckily, one of the advantages of higher-level programming languages such as C is
that you don’t need to concern yourself with the particular memory addresses that are
assigned to variables—they are automatically handled by the system. However, the
knowledge that a unique memory address is associated with each variable will help you
to understand the way pointers operate.
When you apply the address operator to a variable in C, the value that is generated is
the actual address of that variable inside the computer’s memory. (Obviously, this is
where the address operator gets its name.) So, the statement


intPtr = &count;


assigns to intPtrthe address in the computer’s memory that has been assigned to the
variable count.So,if countis located at address 500 and contains the value 10 , this state-
ment assigns the value 500 to intPtr, as depicted in Figure 11.11.


Variable

count

intPtr

500




Address

10

500

Figure 11.11 Pointers and memory addresses.

The address of intPtris shown in Figure 11.11 as –-because its actual value is irrele-
vant for this example.
Applying the indirection operator to a pointer variable, as in the expression


*intPtr


has the effect of treating the value contained in the pointer variable as a memory
address.The value stored at that memory address is then fetched and interpreted in
accordance with the type declared for the pointer variable. So, if intPtris of type point-
er to int, the value stored in the memory address given by *intPtris interpreted as an
integer by the system. In our example, the value stored at memory address 500 is fetched
and interpreted as an integer.The result of the expression is 10, and is of type int.
Storing a value in a location reference by a pointer, as in


*intPtr = 20;


proceeds in a like manner.The contents of intPtris fetched and treated as a memory
address.The specified integer value is then stored at that address. In the preceding state-
ment, the integer value of 20 is, therefore, stored at memory address 500.
At times, system programmers must access particular locations inside the computer’s
memory. In such cases, this knowledge of the way that pointer variables operate proves
helpful.

Free download pdf