Getting input with fgets and outputing the answer in reverse with recursion












-1















This is a sample snippet from a book. I am not understanding how it is printing the string in reverse. The first time reverse is called, the element at 0 is not null assuming of course a valid string was entered. In the else statement, we are calling the function again passing in the address of element at index 1.



So let's say I input "hello". Then I am passing the address of e. The second time reverse is called, however, how is the string being traverse? The index being checked is still 1. Also, it seems to me we are not replacing the values of the array. When we start printing the values with putchar I get so confused that the value at index 0 starts with the last element of the array. I understand that when we use recursion and we hit the base case, and since the items are put on the stack, we start reading them from the top of the stack pointer until the end which is why is in reverse. But here I don't see that happening.



The hard-coded indexes at



reverse( &ptr[1]);
putchar(ptr[0]);


do not make sense to me. I guess I am having difficulty seeing how the string is being traverse when it is the same address being passed each time in the recursion. Please help me understand what is happening.



I have modified the code a bit for simplicity but it does the same thing the one in the book does.



#include <stdio.h>

void reverse(char * ptr);

int main(){
char sentence[10];
printf("enter text n");
fgets(sentence, 10, stdin);
printf("The line is: n");
reverse(sentence);
return 0;
}

void reverse( char * ptr){
if(ptr[0] == ''){
return;
} else{
reverse( &ptr[1]);
putchar(ptr[0]);
printf("n");
}
}









share|improve this question

























  • You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

    – Weather Vane
    Dec 31 '18 at 16:56








  • 1





    I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

    – Some programmer dude
    Dec 31 '18 at 16:56











  • @Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

    – Wirito
    Dec 31 '18 at 17:00











  • @WeatherVane Thanks. I will use a debugger to look into this.

    – Wirito
    Dec 31 '18 at 17:01











  • Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

    – Wirito
    Dec 31 '18 at 17:34
















-1















This is a sample snippet from a book. I am not understanding how it is printing the string in reverse. The first time reverse is called, the element at 0 is not null assuming of course a valid string was entered. In the else statement, we are calling the function again passing in the address of element at index 1.



So let's say I input "hello". Then I am passing the address of e. The second time reverse is called, however, how is the string being traverse? The index being checked is still 1. Also, it seems to me we are not replacing the values of the array. When we start printing the values with putchar I get so confused that the value at index 0 starts with the last element of the array. I understand that when we use recursion and we hit the base case, and since the items are put on the stack, we start reading them from the top of the stack pointer until the end which is why is in reverse. But here I don't see that happening.



The hard-coded indexes at



reverse( &ptr[1]);
putchar(ptr[0]);


do not make sense to me. I guess I am having difficulty seeing how the string is being traverse when it is the same address being passed each time in the recursion. Please help me understand what is happening.



I have modified the code a bit for simplicity but it does the same thing the one in the book does.



#include <stdio.h>

void reverse(char * ptr);

int main(){
char sentence[10];
printf("enter text n");
fgets(sentence, 10, stdin);
printf("The line is: n");
reverse(sentence);
return 0;
}

void reverse( char * ptr){
if(ptr[0] == ''){
return;
} else{
reverse( &ptr[1]);
putchar(ptr[0]);
printf("n");
}
}









share|improve this question

























  • You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

    – Weather Vane
    Dec 31 '18 at 16:56








  • 1





    I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

    – Some programmer dude
    Dec 31 '18 at 16:56











  • @Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

    – Wirito
    Dec 31 '18 at 17:00











  • @WeatherVane Thanks. I will use a debugger to look into this.

    – Wirito
    Dec 31 '18 at 17:01











  • Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

    – Wirito
    Dec 31 '18 at 17:34














-1












-1








-1








This is a sample snippet from a book. I am not understanding how it is printing the string in reverse. The first time reverse is called, the element at 0 is not null assuming of course a valid string was entered. In the else statement, we are calling the function again passing in the address of element at index 1.



So let's say I input "hello". Then I am passing the address of e. The second time reverse is called, however, how is the string being traverse? The index being checked is still 1. Also, it seems to me we are not replacing the values of the array. When we start printing the values with putchar I get so confused that the value at index 0 starts with the last element of the array. I understand that when we use recursion and we hit the base case, and since the items are put on the stack, we start reading them from the top of the stack pointer until the end which is why is in reverse. But here I don't see that happening.



The hard-coded indexes at



reverse( &ptr[1]);
putchar(ptr[0]);


do not make sense to me. I guess I am having difficulty seeing how the string is being traverse when it is the same address being passed each time in the recursion. Please help me understand what is happening.



I have modified the code a bit for simplicity but it does the same thing the one in the book does.



#include <stdio.h>

void reverse(char * ptr);

int main(){
char sentence[10];
printf("enter text n");
fgets(sentence, 10, stdin);
printf("The line is: n");
reverse(sentence);
return 0;
}

void reverse( char * ptr){
if(ptr[0] == ''){
return;
} else{
reverse( &ptr[1]);
putchar(ptr[0]);
printf("n");
}
}









share|improve this question
















This is a sample snippet from a book. I am not understanding how it is printing the string in reverse. The first time reverse is called, the element at 0 is not null assuming of course a valid string was entered. In the else statement, we are calling the function again passing in the address of element at index 1.



So let's say I input "hello". Then I am passing the address of e. The second time reverse is called, however, how is the string being traverse? The index being checked is still 1. Also, it seems to me we are not replacing the values of the array. When we start printing the values with putchar I get so confused that the value at index 0 starts with the last element of the array. I understand that when we use recursion and we hit the base case, and since the items are put on the stack, we start reading them from the top of the stack pointer until the end which is why is in reverse. But here I don't see that happening.



The hard-coded indexes at



reverse( &ptr[1]);
putchar(ptr[0]);


do not make sense to me. I guess I am having difficulty seeing how the string is being traverse when it is the same address being passed each time in the recursion. Please help me understand what is happening.



I have modified the code a bit for simplicity but it does the same thing the one in the book does.



#include <stdio.h>

void reverse(char * ptr);

int main(){
char sentence[10];
printf("enter text n");
fgets(sentence, 10, stdin);
printf("The line is: n");
reverse(sentence);
return 0;
}

void reverse( char * ptr){
if(ptr[0] == ''){
return;
} else{
reverse( &ptr[1]);
putchar(ptr[0]);
printf("n");
}
}






c arrays recursion fgets putchar






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 31 '18 at 18:36









usr2564301

17.8k73370




17.8k73370










asked Dec 31 '18 at 16:54









WiritoWirito

93




93













  • You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

    – Weather Vane
    Dec 31 '18 at 16:56








  • 1





    I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

    – Some programmer dude
    Dec 31 '18 at 16:56











  • @Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

    – Wirito
    Dec 31 '18 at 17:00











  • @WeatherVane Thanks. I will use a debugger to look into this.

    – Wirito
    Dec 31 '18 at 17:01











  • Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

    – Wirito
    Dec 31 '18 at 17:34



















  • You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

    – Weather Vane
    Dec 31 '18 at 16:56








  • 1





    I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

    – Some programmer dude
    Dec 31 '18 at 16:56











  • @Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

    – Wirito
    Dec 31 '18 at 17:00











  • @WeatherVane Thanks. I will use a debugger to look into this.

    – Wirito
    Dec 31 '18 at 17:01











  • Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

    – Wirito
    Dec 31 '18 at 17:34

















You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

– Weather Vane
Dec 31 '18 at 16:56







You pass &ptr[1] to the recursion, so each time the string passed begins with the next character.

– Weather Vane
Dec 31 '18 at 16:56






1




1





I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

– Some programmer dude
Dec 31 '18 at 16:56





I suggest you take some time to learn how to use a debugger. With one you can step through code line by line, and step into function calls, all while monitoring variables and their values. If you do that with the recursive calls, keeping an eye on ptr[0] and ptr[1], it should hopefully become clear what's happening.

– Some programmer dude
Dec 31 '18 at 16:56













@Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

– Wirito
Dec 31 '18 at 17:00





@Someprogrammerdude Oh shoot! Of course. I know how to use the debugger I just didn't think about GDB. I'll do that right now!

– Wirito
Dec 31 '18 at 17:00













@WeatherVane Thanks. I will use a debugger to look into this.

– Wirito
Dec 31 '18 at 17:01





@WeatherVane Thanks. I will use a debugger to look into this.

– Wirito
Dec 31 '18 at 17:01













Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

– Wirito
Dec 31 '18 at 17:34





Ahhh this is so cool!! I have never done recursion this way in C as I started out with Java. I see now what is happening. Is not that we are traversing the string in the traditional way but by sending in the starting address each time index at 0 and 1 change because we are "eating up" the array as we go. Thanks for the responses :)

– Wirito
Dec 31 '18 at 17:34












1 Answer
1






active

oldest

votes


















0














The &ptr[1] is equivalent to ptr + 1. Now, if you think of ptr as a number (which it is, really) it should be obvious that it's not the same number being passed every time, but rather one greater for each level of recursion. It's basically passing a substring starting from the second character, only in C the substring is not a separate object but rather a pointer to a different position in the same string.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53989687%2fgetting-input-with-fgets-and-outputing-the-answer-in-reverse-with-recursion%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The &ptr[1] is equivalent to ptr + 1. Now, if you think of ptr as a number (which it is, really) it should be obvious that it's not the same number being passed every time, but rather one greater for each level of recursion. It's basically passing a substring starting from the second character, only in C the substring is not a separate object but rather a pointer to a different position in the same string.






    share|improve this answer




























      0














      The &ptr[1] is equivalent to ptr + 1. Now, if you think of ptr as a number (which it is, really) it should be obvious that it's not the same number being passed every time, but rather one greater for each level of recursion. It's basically passing a substring starting from the second character, only in C the substring is not a separate object but rather a pointer to a different position in the same string.






      share|improve this answer


























        0












        0








        0







        The &ptr[1] is equivalent to ptr + 1. Now, if you think of ptr as a number (which it is, really) it should be obvious that it's not the same number being passed every time, but rather one greater for each level of recursion. It's basically passing a substring starting from the second character, only in C the substring is not a separate object but rather a pointer to a different position in the same string.






        share|improve this answer













        The &ptr[1] is equivalent to ptr + 1. Now, if you think of ptr as a number (which it is, really) it should be obvious that it's not the same number being passed every time, but rather one greater for each level of recursion. It's basically passing a substring starting from the second character, only in C the substring is not a separate object but rather a pointer to a different position in the same string.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 18:45









        ArkkuArkku

        30.5k54866




        30.5k54866
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53989687%2fgetting-input-with-fgets-and-outputing-the-answer-in-reverse-with-recursion%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas