as

Thursday, 13 November 2014

Pointers and Strings.


Since strings are stored in the form of character arrays, we can use pointers to manipulate the strings.

Below program shows how we can use pointers to handle the strings in C.

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

      char *s1, *s2, *s3;
      int i=0,j=0;

      //Below statement will reserve 5 bytes and initialize s1 to it
      s1 = "Bill";
      s2 = "Gates";

      //Below statement will reserve 5 bytes and initialize s3 to it
      s3 = malloc(5);
     
      //find the length of s1 using pointer
      while(*(s1+i))
      {
      i++;
      }
      printf ("Length of the string s1 %s is %d \n", s1,i);
                i--;   
      //========================================
      //reverse the string using pointer
      while(i>=0)
      {
      *(s3+j) = *(s1+i);
      i--;
      j++;
      }
                *(s3+j) = '\0';
      printf ("Reverse of the string s3 is %s \n", s3);
      //========================================
      //Copy the string s1 to s3
      i=0;
      while(*(s1+i))
      {
     
      *(s3+i) = *(s1+i);
      i++;
      }
      printf ("S1 copied to s3 %s \n", s3);

      //========================================
      s3 = "sgaarsalunke";
      printf ("s3 %s \n", s3);
     

}





No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis