What is Pointer in c with example ?

Pointer

A pointer is a variable that holds address (memory location) of another variable rather than actual value. Also, a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location.  So, a pointer variable points to a memory location and we can access and change the contents of this memory location via the pointer. Pointers are used frequently in C, as they have a number of useful applications. In particular, pointers provide a way to return multiple data items from a function via function arguments.
 Pointer Declaration 
Pointer variables, like all other variables, must be declared before they may be used in a C program. We use asterisk (*) to do so. Its general form is: 
ata-type *ptrvar;
 For example,
 int* ptr; 
This statement declares the variable ptr as a pointer to int, that is, ptr can hold address of an integer variable.
 Once we declare a pointer variable we can point by it to something. We can do this by assigning to the pointer the address of the variable you want to point as in the following example:
  int var=11,*ptr;
 ptr=&var;
 This places the address where var is stores into the variable ptr. For example, if var is stored in memory 21260 address then the variable ptr has the value 21260.
 We can access the contents of the variable pointed by pointer using an asterisk (*) in front of a variable name. 
For example:

#include<stdio.h>
 #include<conio.h>
  void main()
   {  
   int var=11,*ptr;
        clrscr();
printf("%d\n",var);
   printf("%d\n",&var); 
   printf("%d\n",*&var); 
    ptr=&var;     
printf("%d\n",ptr);
 //prints address of var 
   printf("%d\n",*ptr);
//prints 11
     *ptr=45;  
    printf("%d\n",var);
//prints 45 
 printf("%d\n",*ptr);
  //prints 45 
    getch();

The operator „&‟ is called “address of” operator. The expression &var returns the address of the variable var. The operator „*‟ called “value at address” operator. It gives the value stored at a particular address. The “value at address” operator is also called “indirection operator”. 


No comments

Powered by Blogger.