Tuesday 25 October 2016

POINTERS IN C

USES OF POINTERS:-

  • Dynamic Memory Allocation ( D M A)
  •  A Function can return more than one value
  • Implementing data structures
  • call by reference is possible by pointer

ADDRESS OPERATOR:- ( &)

        In C  '&' is an address  operator. Which returns address of a variables.

Ex: -

              int  a ;

a  is integer type of variable. 

&a means address of a variable a.


/* Program for printing address of a variable */


                            #include<stdio.h>
                            void main( )
                            {

                             int a;
                             printf("enter a value\n ");
                             scanf("%d",&a);
                             printf("the variable  a have =%d", a);
                            printf("the address of a is =%p",&a);
                          
                           }

POINTER VARIABLE:-

                                    Pointer variables is also same as a normal variables. But the only difference is normal variables holds  the values or data. But the pointer variables holds the 
address of another same type of variable.

Syntax:-

          Datatype * pointer_variable_name;

Ex:-

             int *ptr;
            char *ch;
            float *f;

  • Asterisk " * "   is an indirection operation, which can read as " values at the address ". Its nothing but a dereferencing a value.
/* Program for dereferencing a value*/

                                     #include<stdio.h>
                                    void main( )
                                     {
                                           int a; 
                                           printf("enter a value\n");
                                          scanf("%d",&a);ekrnfkj
                                          printf("the value of a=%d",a);
                                           printf("the value of a=%p",&a);
                                         printf("the value of a=%d",*(&a));
                                   }

Assigning a variable address to a pointer variable:-

       Address of a variable is assigned to a pointer variable by using assignment operator.

Ex:-

        int a;
        int *ptr; 

       ptr=&a;


here,   the address of a variable a is assigned to a pointer variable ptr. 

i.e    ptr holds the address of a;



// Program for how to hold the address of a variable

#include<stdio.h> 
void main ( )  
 {
int a,*ptr;
ptr=&a;
printf("enter a variable\n");
scanf("%d",&a);
printf("value of a =%d\n",a);
printf("value of ptr =%p\n",p);
printf("address of a =%p\n",&a);
printf("ptr pointing tthe value =%d\n",*ptr);
}

No comments:

Post a Comment