Our social:

How to Reverse String using Pointer in C

In my last post I had discussed about how to reverse a string. In this post I am showing another method of reversing a string. I will use a pointer here to reverse the string. In this way I took my input in an character array and then assigned the array into a character type pointer. After that I searched the NULL character using pointer asthmatics. And finally printed the string using pointer in reverse order. Now see the code:



#include <stdio.h>

int main()
{
    char str[1000], *ptr;
    int i, len;
    printf("Enter a string: ");
    gets(str);
    ptr = str;
    for(i=0;i<1000;i++){
        if(*ptr == '\0')  break;
        ptr++;
    }
    len = i;
    ptr--;
    printf("Reversed String: ");
    for(i=len; i>0; i--){
        printf("%c",*ptr--);
    }
    return 0;
}