Reverse a string using pointers

C program to reverse a string using pointers

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50

void main()
{
	char str[MAX], rev[MAX];
    char *ptr1, *ptr2;
    int len;

    printf("Enter any string\t:");
    gets(str);

    ptr1 = str;
    ptr2 = rev;
    len = 0;

    while(*(ptr1++))
        len++;

    ptr1--;

    while(len>0)
    {
        ptr1--;
        *ptr2 = *ptr1;
        ptr2++;
        len--;
    }
    *ptr2 = '\0';

    printf("\nOriginal string\t:%s",str);
    printf("\nReversed string\t:%s",rev);

    getch();
}

Output

Enter any string        :welcome

Original string :welcome
Reversed string :emoclew

Explanation

In the above program, a string is taken as an input from the user, and stored in some variable named say 'str'. Another variable 'rev' is also taken, in which reverse of the string is stored. Two pointers 'ptr1' and 'ptr2' are taken that points to 'str' and 'rev' respectively. 'ptr1' and 'ptr2' points at the first character of their respective strings using the statement
ptr1 = str;
ptr2 = rev;

To reverse the string, we have to first calculate the length of the string and point its pointer 'ptr1' at the end of the string.
This is done using the code,
while(*(ptr1++))
len++;
ptr--;
Now, 'len' contains the length of the string, and 'ptr' points to last character of the string.

Now, while loop is executed 'len' number of times and character from 'str' is copied to 'rev' using pointers
*ptr2 = *ptr1;
'ptr1' is decreased by 1, so that it points to the previous character which is to be copied in 'rev' and, 'ptr2' is increased by 1, so that it points to the position where character is to be copied.
ptr2++;
len--;
Each string is NULL terminated. So, 'rev' string is also NULL terminated explicitly using the statement,
*ptr2 = '\0';