C - Pointer
C - Pointer
C – Pointer
If you want to be proficient in the writing of code in the C
programming language, you must have a thorough
working knowledge of how to use pointers.
Some C programming tasks are performed more easily
with pointers, and other tasks, such as dynamic memory
allocation, cannot be performed without using pointers.
So it becomes necessary to learn pointers to become a
perfect C programmer.
As you know, every variable is a memory location and
every memory location has its address defined which can
be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following
example, which will print the address of the variables
defined:
C – Pointer
dataType *var_name;
Here,
dataType is the pointer's base type; it must be a valid C data
type(i.e., int, float, char etc).
var_name is the name of the pointer variable.
The asterisk * you used to declare a pointer is the same
asterisk that you use for multiplication. However, in this
statement the asterisk is being used to designate a variable as
a pointer.
Pointer
Following are the valid pointer declaration:
++ptr
Now, after the above operation, the ptr will point to the location
1004 because each time ptr is incremented, it will point to the
next integer location which is 4 bytes next to the current location.
If ptr points to a character whose address is 1000, then above
operation will point to the location 1001 because next character
will be available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array
because the variable pointer can be incremented, unlike the
array name which cannot be incremented because it is a
constant pointer.
The following program increments the variable pointer to
access each succeeding element of the array (see next slide).
Incrementing a Pointer
Decrementing a Pointer
The same considerations apply to decrementing a
pointer, which decreases its value by the number of
bytes of its data type as shown below:
Pointer * and ++
Pointer Comparisons
Pointers may be compared by using relational
operators, such as ==, <, and >.
If p1 and p2 point to variables that are related to
each other, such as elements of the same array,
then p1 and p2 can be meaningfully compared.
The following program modifies the previous
example one by incrementing the variable
pointer as long as the address to which it points
is either less than or equal to the address of the
last element of the array, which is &var[MAX - 1]
(see next slide).
Pointer Comparisons
Array of pointers
Before we understand the concept of arrays of
pointers, let us consider the following example,
which makes use of an array of 3 integers:
Array of pointers
int *ptr[ ];