Pointer Tutorial in Class
Pointer Tutorial in Class
Pointer Tutorial in Class
Here, type is the pointer's base type; it must be a valid C data type and 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. Following are the valid pointer declaration:
int
double
float
char
*ip;
*dp;
*fp;
*ch
/*
/*
/*
/*
pointer
pointer
pointer
pointer
to
to
to
to
an integer */
a double */
a float */
a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
How to use Pointers?
There are few important operations, which we will do with the help of pointers very frequently.
(a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally
access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.
Following example makes use of these operations:
// Program 1.
#include <stdio.h>
int main ()
{
int var = 20;
int *ip;
When the above code is compiled and executed, it produces result something as
follows:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Complete program 1 and compare output with proposed above. Did you receive the same
results? Why?
Example to demonstrate working of pointers
Complete program 2 and compare output with proposed above. Did you
receive the same results? Why?
// Program 2.
Output:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
temp = &count;
*temp = 20;
temp = ∑
*temp = count;
printf("count = %d, *temp = %d, sum = %d\n", count, *temp, sum );
// Program 5
The string The day is done is stored somewhere in memory, and its possible to
increment and decrement pointer variable to access the string individual
characters:
char *verse = The day is done;
So, in this case:
verse - assign to address of the character T;
verse +1 - assign to address of the character h;