Introduction to Pointers

Introduction to pointer

Pointer are variable that contain memory address as their values. A variable name directly reference a value but A pointer indirectly reference a value. Referencing a value through a pointer is called indirection. A pointer variable must be declared before it can be used.

 

Example of pointer declaration

int *num;          /* declare a pointer to an int */

char *str;         /* declare a pointer to an char */

float *a;           /* declare a pointer to an float */

double *b;       /* declare a pointer to an double */

 

The asterik, when used  as above  in the declaration, tells the compiler that the variable is to be a pointer, and the type of data that the pointer points to, but not the name of variable poited to.

 

Use of & and *

& is address operator which gives or produces the memory address of a data variable

* is a derefrencing operator which provides the contents in the memory location specified by a pointer.

The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to.

The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to.

A simple example to print value and address of a variable .

int main( ){

int  num = 100 ;

printf ( “Address of num = %u\n”, &num ) ;

printf ( “Value of num = %d\n”, num ) ;

return 0;

}

Output:

Address of num = 4000      /* It may print different on other machine */

Value of num = 100

int  num = 100 ;

This declaration tells the C compiler to:

(a) Reserve space in memory to hold the integer value.

(b) Associate the name num with this memory location.

(c) Store the value 100 at this location.

We may represents  memory location by the following memory map.

Location name         =           num

Value at location     =         1000

Address of location =        4000

Now take a pointer variable and assign address of num to that pointer variable. And see graphical representation.

int     *ptr;         /* ptr is pointer to int */

ptr = #     /* ptr is now pointing to num */

 Location name         =        ptr

Value at location     =        4000

Address of ptr          =        8000

int num1 = 50;

num1 = *ptr;        /* num1 is now 100 */

Benefits of pointer

  1. pointers can be used to pass address of variable to called function.(This is called call by reference).
  2. pointer can be used to return multiple data types.
  3. Pointer can be used to access the value of other variables.
A pointer may be incremented or decremented.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.