Thursday, July 14, 2011

INTRODUCTION OF POINTER

INTRODUCTION OF POINTER
Pointers are variables that hold addresses. They provide much power and utility for the programmer to access and manipulate data in ways not seen in some other languages.
A pointer is a special type of variable that contains a memory address rather than a data value. Just as data is modified when a normal variable is used, the value of the address stored in a pointer is modified as a pointer variable is manipulated.
Usually, the address stored in the pointer is the address of some other variable.
int *ptr;
ptr = &count /* Stores the address of count in ptr */   
To get the value that is stored at the memory location in the pointer it is necessary to dereference the pointer. Dereferencing is done with the unary operator "*".
int total;
total = *ptr;
    /* The value in the address stored in ptr is assigned to total */
 
Example 1: To take input and output for integer pointer variable
#include<string.h>   
#include<conio.h>    
main()
{
    int a;
    int *x;
 
    //taking input for general variable
    scanf("%d", &a);
    //taking input for printer
    scanf("%d", x);
 
    //displaying value for general variable
    printf("%d", a);
    //displaying value for pointer variable
    printf("%d", *x);
 
    getch();
}
Example 2: Program to convert uppercase string into lowercase using pointer
#include<string.h>   
#include<conio.h>    
main()
{
    char *str;
    int i;
 
    printf("Enter value for string:");
    scanf("%s", str);
   
    for(i=0; *(str+i)!='\0'; i++)
          if(*(str+i)>= 'A' && *(str+i)<= 'Z')
                *(str+i) = *(str+i) + 32;
 
    printf("converted into Lower case sting is %s ", str);
 
    getch();
}
 
Example 3: Write a program to input name of person. Reorder record in alphabetical order of name.
#include<stdio.h>
#include<string.h>   
#include<conio.h>
main()
{
    char *name[10], temp[25];
    int i, j;
 
    /*taking input for name and age*/
    for(i=0; i<10; i++)
          scanf("%s", name[i]);
 
    /*reordering record in order of name */
    for(i=0; i<10; i++)
          for(j=i+1; j<10; j++)
          {
                if(strcmp(name[i], name[j]) > 0)
                {
      //swapping name
      strcpy(temp, name[i]);
      strcpy(name[i], name[j]);
      strcpy(name[j], temp)  
                }    
          }
/*Displaying the reordered name */
    for(i=0; i<10; i++)
          printf("%s", name[i]);
 
    getch();
}

0 comments:

Post a Comment