An Introduction to Pointers

Pointers are variables that hold address of another variable of same data type. Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language. Although pointer may appear little confusing and complicated in the beginning, but trust me it’s a powerful tool and handy to use once it’s mastered.

Benefit of Using Pointers:

  • Pointers are more efficient in handling Array and Structure.
  • Pointer saves the memory space.
  • It reduces length and the program execution time.
  • Pointers are used to allocate memory dynamically.

Concept of Pointer:

Whenever a variable is declared, system will allocate a location to that variable in the memory, to hold value. This location will have its own address number.

Let us assume that, system has allocated memory location 80F for a variable a.

int a = 10 ;

We can access the value 10 by either using the variable name a or the address 80F. Since the memory addresses are simply numbers they can be assigned to some other variable. The variable that holds memory address are called pointer variables. A pointer variable is therefore nothing but a variable that contains an address, which is a location of another variable. Value of pointer variable will be stored in another memory location.

Declaring a Pointer Variable:

Syntax of pointer declaration is:

data-type *pointer_name;

Data type of pointer must be same as the variable, which the pointer is pointing.

Initialization of Pointer variable:

Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable contains address of variable of same data type. In C language address operator & is used to determine the address of a variable. The & returns the address of the variable associated with it.

int a = 10 ;
int *ptr ;        //pointer declaration
ptr = &a ;        //pointer initialization

or we can mention

int *ptr = &a ;      //initialization and declaration together

Pointer variable always points to same type of data.

float a;
int *ptr;
ptr = &a;    //ERROR due to type mismatch.

Dereferencing of Pointer:

Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is dereferenced, using the indirection operator *.

int a,*p;
a = 10;
p = &a;

printf("%d",*p);    //this will print the value of a.

printf("%d",*(&a));  //this will also print the value of a.

printf("%u",&a);  //this will print the address of a.

printf("%u",p);  //this will also print the address of a.

printf("%u",&p);  //this will also print the address of p.

Author
Mr.Rahul Agarwal
Associate Professor, Department of CS & IT
Biyani Group of Colleges,Jaipur