C Language: Pointers 21

Self-defined function using pointers(Selfrev())

Important Question:

C program using pointers, write a user defined function named “selfrev()” to reverse the string?

Example:

1.
n=”HELLO”
Output:
OLLEH
2.
n=”computer”
Output:
retupmoc

#include<stdio.h>
#include<string.h>
void selfrev(char *p) 
{ 
    int len, i; 
    char *b_ptr, *e_ptr, t; 
    /*
    b_ptr: pointer to the first character
    e_ptr: pointer to the end character
    */
    len = strlen(p); 
    // pointer variables b_ptr and e_ptr are initilized by p 
    b_ptr = p; 
    e_ptr = p; 
  
    // Make sure that e_ptr points to the last character 
	//of the string 
    for (i=0;i<len-1;i++)
        e_ptr++; 
  
    // Now we have to Swap the char from start and end 
    for (i=0;i<len/2;i++) 
	{ 
 	    t = *e_ptr; 
        *e_ptr = *b_ptr; 
        *b_ptr = t; 
  
        b_ptr++; 
        e_ptr--; 
    } 
} 
int main()
{
  char n[20];
  printf("Enter any string ");
  gets(n);
  selfrev(n);
  printf("String in reverse is %s\n",n);
  return(0);
}

Output:

Enter any string Computer
String in reverse is retupmoC

Enter any string hello
String in reverse is olleh