C Program to reverse a string using command line arguments

This article explains how to reverse a given string in place.



The input is taken by user using command line arguments.
input = $ a.out Subhash
result = hsahbuS
In above example “Subhash” is the string which is stored in argv[1]. So argv[1] = “AAHA”.The complete string present in the input will be reversed.




1.Take the input from the user.
2.Use malloc and allocate memory for the given input.
3.Now the pointer(p) created will be pointing to the allocated memory.
4.Copy the contents of the input given using command line argument into the memory allocated (p[k] = argv[i][j]) and input character ‘ ‘ and ‘\0’ in appropriate position.
5.Call the function my_strrev(p) by passing the pointer p.
6.In the function defination ,consider two variables i and j, such that i points to the first character and j to the last character, perform the swapping function until (i<j)is satisfied.
7.When (i < j) condition fails the condition comes out of the loop and prints the required reverse string.


Source code:


void my_strrev(char *);
int main(int argc,char *argv[])
             int i,j,k=0,sum=0;
                          sum = sum+strlen(argv[i]);
              sum = sum + (argc-1);
             char *p = malloc(sum);
            for(i = 1; i <argc; i++)
                      for(j = 0;argv[i][j]!='\0';j++)
                               p[k] = argv[i][j];
                   p[k++]=' ';
          p[k] = '\0';
          printf("input : %s",p);
void my_strrev(char *p)
          int i,j;
          for(i=0,j=strlen(p)-1; i<j; i++,j--)
                      int t;
                     t = *(p+i);
                    *(p+i) = *(p+j);
                   *(p+j) = t;
          printf("\nreverse = %s\n",p);


This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.



Subhash Embedded Classes is one of the Best Embedded Systems Training Institute in Bangalore

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.