C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Reverse string using pointers

C Program: Reverse string using pointers

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[100], rev[100];

    char *ptr1, *ptr2;

    int length, i;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Remove newline character if present

    length = strlen(str);

    if (str[length - 1] == '\n') {

        str[length - 1] = '\0';

        length--;

    }

 

    // Set pointers

    ptr1 = str;             // Points to start of string

    ptr2 = rev + length - 1; // Points to end of reverse string

 

    // Null terminate reverse string

    rev[length] = '\0';

 

    // Copy characters in reverse order

    for (i = 0; i < length; i++) {

        *ptr2-- = *ptr1++;

    }

 

    // Display reversed string

    printf("Reversed string: %s\n", rev);

 

    return 0;

}

Output

 
OUTPUT :
Enter a string: ITDeveloper
Reversed string: repoleveDTI

Explanation

  • The program uses two pointers:
    • ptr1 points to the beginning of the original string.
    • ptr2 points to the end of the rev array.
  • Characters are copied from end to start using pointer arithmetic.
  • Finally, the reversed string is printed.