Page 169 - DCAP507_SYSTEM_SOFTWARE
P. 169
Unit 10: Programming Languages Concept (I)
10.6.1 Accessing of Pointers Notes
Pointers are often thought to be the most difficult aspect of C. It's true that many people have
various problems with pointers, and that many programs founder on pointer-related bugs.
Actually, though, many of the problems are not so much with the pointers per se but rather with
the memory they point to, and more specifically, when there isn't any valid memory, which
they point to. As long as you're careful to ensure that the pointers in your programs always
point to valid memory, pointers can be useful, powerful, and relatively trouble-free tools.
A pointer is a variable that points at, or refers to, another variable. That is, if we have a pointer
variable of type “pointer to int,” it might point to the int variable i, or to the third cell of the int
array a. Given a pointer variable, we can ask questions like, “What's the value of the variable
that this pointer points to?”
When we declare a variable
int a = 10;
In the main memory following things happen
a 10
1001
where a is the name of the variable & 1001 is the address of the variable in the memory.
If we declare a variable to store 1001, that variable is known as a pointer. Thus a pointer is a
variable that stores the address of another variable.
Basic Pointer Operations
The first things to do with pointers are to declare a pointer variable, set it to point somewhere,
and finally manipulate the value that it points to. A simple pointer declaration looks like this:
int *ip;
This declaration looks like our earlier declarations, with one obvious difference: that asterisk.
The asterisk means that ip, the variable we're declaring, is not of type int, but rather of type
pointer-to-int. (Another way of looking at it is that *ip, which as we'll see is the value pointed to
by ip, will be an int.)
We may think of setting a pointer variable to point to another variable as a two-step process:
first we generate a pointer to that other variable, then we assign this new pointer to the pointer
variable. We can say (but we have to be careful when we're saying it) that a pointer variable has
a value, and that its value is “pointer to that other variable”. This will make more sense when we
see how to generate pointer values.
Pointers (that is, pointer values) are generated with the ''address-of'' operator &, which we can
also think of as the “pointer-to” operator. We demonstrate this by declaring (and initializing) an
int variable i, and then setting ip to point to it:
int i = 5;
ip = &i;
The assignment expression ip = &i; contains both parts of the “two-step process”: &i generates a
pointer to i, and the assignment operator assigns the new pointer to (that is, places it ''in'') the
variable ip. Now ip “points to” i.
LOVELY PROFESSIONAL UNIVERSITY 163