Within the computer's memory, every stored data item occupies one or more contiguous memory cells (i.e. adjacent words or bytes). The number of memory cells required to store a data item depends on the type of data item.For example, a single character will typically be stored in one byte (8 bits) of memory; an integer usually requires two contiguous bytes; a floating-point number may require four contiguous bytes; and a double precision quantity may require eight contiguous bytes.
Suppose v is a variable that represents some particular data item.The compiler will automatically assign memory cells for this data item.The data item can then be accessed if we know the location (i.e. the address) of the first memory cell. The address of v's memory location can be determined by the expression &v, where & is a unary operator, called the address operator, that evaluates the address of its operand.
Now let us assign the address of v to another variable, pv. Thus,
pv = &v
This new variable is called a pointer to v, since it "points" to the location where v is stored in memory.Thus, pv is referred to as a pointer variable.
The data item represented by v (i.e. , the data item stored in v's memory cells) can be accessed by the expression *pv, where * is unary operator, called the indirection operator, that operates only on a pointer variable. Therefore, *pv and v both represent the same data item (i.e, the contents of the memory cells). Furthermore, if we write pv = &v and u = *pv, then u and v will both represent the same value; i.e., the value of v will indirectly be assigned to u.
Consider the simple C program shown below.
#include < stdio.h >
main ()
{
int u1, u2;
int v = 3;
int *pv; /* pv pointer to v*/
u1= 2* (v+5); /*ordinary expression*/
pv = &v;
u2= 2* (*pv +5); /*equivalent expression*/
printf("\nu1=%d u2=%d", u1, u2);
}
This program involves the use of two integer expressions. The first, 2 * (v+5), is an ordinary arithmetic expression whereas the second, 2* (*pv+5), involves the use of a pointer. The expressions are equivalent, since v and *pv each represent the same integer value.
The following output is generated when the program is executed.
u1=16 u2=16
No comments:
Post a Comment