Reverse of string using pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandeep n
    New Member
    • Oct 2011
    • 3

    Reverse of string using pointers

    I am not getting reverse string using following code,

    can u explain where i did mistake and correct it

    with regards
    sandeep

    code-->>>

    Code:
    #include<stdio.h>
    #include<string.h>
    main()
    {
    	char s1[100],s2[100],*p,*q;
    	gets(s1);
    	p=s1;q=s2;
    	while(*p!='\0')
    		p++;
    	while(p>=&s1[0])
    	{
    		*q++=*p--;
    	}
    	*q='\0';
    	printf("\ngiven string--->%s\n",s1);
    	printf("\nreverse string--->%s\n",s2);
    }
    Last edited by Meetee; Oct 12 '11, 09:45 AM. Reason: code tags added
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    I think the first thing that happens is that you copy the NULL into s2[0] so when you try to print s2 nothing comes out.

    A couple of other good habits:
    1. use fgets or getline instead of gets http://www.crasseux.com/books/ctutorial/gets.html
    2. It's a good habit to always initialize variables - I'm referring specifically to s1 and s2.
    3. you don't need the first loop to find the end of s1, you can use strlen for that

    Comment

    • sandeep n
      New Member
      • Oct 2011
      • 3

      #3
      You know that
      *q++=*p--;
      reduces to
      *q=*p;
      q++;p++;
      for the 1st instant of the loop q points to first element of the s2 and s1 points to last element of the s1
      *q=*p for the first instant should copy last element of s1 into first element of s2

      Is not it...

      Please clarify clearly

      Comment

      • whodgson
        Contributor
        • Jan 2007
        • 542

        #4
        After the pointers are positioned at each end of the SAME string just swap them (what they are pointing to) using the swap() function defined in the header <algorithm>.

        Comment

        • sandeep n
          New Member
          • Oct 2011
          • 3

          #5
          Good Idea

          but what's the wrong in the code?

          Comment

          • stereomike
            New Member
            • Oct 2011
            • 1

            #6
            Originally posted by sandeep n
            Good Idea

            but what's the wrong in the code?
            s2[0] is '\0'
            s2+1 will be the reversed string.

            Put p--; in between the two while loops.

            Comment

            Working...