Pointers and Strings


Pointers and Strings:

            Operations on string can be performed in an easier way using pointers.  A String is a character array which is declared as follows.
                                    char str [10];

            Pointers to a string can be declared using a variable which holds base address of the string. Pointers to a string can be declared as follows.
                                                char *p;

The base address of a string can be stored in a pointer variable as follows.
                                                p=str;
  WAP to read and display a string using pointers.
#include<stdio.h>
#include<conio.h>
void main ()
{
      char str[10], *p;
      printf(“enter any string”);

      gets(str);
p=str;
while(*p!=’\0’)
{
      printf(“%c”,*p);
      p++;
 }
}




Write a program to find length of a string using pointers.

#include<stdio.h>
#include<conio.h>

void main ()
      {
                  char str[10], *p,*q;
                  printf(“enter any string”);
                  gets (str);
                  p=str;
                  q=p;
while(*p!=’\0’)
{
p++;
}
printf(“length=%d”,p-q);
}




No comments:

Post a Comment