Pointer string reverse using recursive call giving unexpected output

Discussion in 'C' started by awnish, Oct 9, 2015.

  1. awnish

    awnish New Member

    Joined:
    Oct 6, 2015
    Messages:
    5
    Likes Received:
    1
    Trophy Points:
    0
    Location:
    pune
    Code:
    /* THE BELOW CODE IS WORKING 
    
    #include<stdio.h>
    #include<string.h>
    void string_rev(char*);
    
    int main()
    {
    	char str[20]="ABCDEF GHIJKL";
    	string_rev(str);
    }
    
    void string_rev(char *ptr)
    {
    	int len = strlen(ptr);
    	ptr += (len-1);
    	for( ; len>0 ; --len,--ptr)
    		printf("%c\n",*ptr);
    }
    */
    
    /* THE BELOW CODE IS NOT WORKING */
    #include<stdio.h>
    void string_rev(char*);
    int main()
    {
    	char str[]="abcd";
    	string_rev(str);
    	printf("\n");
    }
    void string_rev(char *ptr)
    {
    	while((*ptr)!='\0')
    	{
    		string_rev(++ptr);
    		printf("%c\n ",*ptr);
    	}
    }
    //Incrementing the pointer using increment operator and then calling the function again is not working . Giving output of input string abcd as dcdbdcd .Using (ptr+1) or (1+ptr) as an argument to the function call is giving infinite loop .
    Code:
    /* OUTPUT
    awnish@awnish:~$ ./a.out 
    	address = -587940896 
    	address = -587940895 
    	address = -587940894 
    	address = -587940893 
    d	address = -587940893 
    c	address = -587940894 
    	address = -587940893 
    d	address = -587940893 
    b	address = -587940895 
    	address = -587940894 
    	address = -587940893 
    d	address = -587940893 
    c	address = -587940894 
    	address = -587940893 
    d	address = -587940893 
    */
     
  2. awnish

    awnish New Member

    Joined:
    Oct 6, 2015
    Messages:
    5
    Likes Received:
    1
    Trophy Points:
    0
    Location:
    pune
    please dont conside the output pasted above . It is giving the address as well
    The output of the above program is
    d

    c

    d

    b

    d

    c

    d
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Change while to if and see if that fixes it.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice