slen function with recursion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kalar
    New Member
    • Aug 2007
    • 82

    slen function with recursion

    I want to make a function slen (recursive) with arguments a pointer to string and returns the length of the string.I make this but i have segmetation fault.
    Code:
    #include <stdio.h>
    
    int slen(char *p);
    
    int main(void)
    {
     char *s="hello";
     int num;
    
     num=slen(s);
    
     printf("%d\n", num);
    
     return 0;
    }
    
    int slen(char *p)
    {
     if (*p=='\0')
       return 0;
     else
       return(slen(p++) +1);
    }
    any idea?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by kalar
    any idea?
    Yep, make that ++p instead of p++.

    kind regards,

    Jos

    Comment

    • kalar
      New Member
      • Aug 2007
      • 82

      #3
      thank you very much .I was looking about half an hour and i couldn't find where the mistake was

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by kalar
        thank you very much .I was looking about half an hour and i couldn't find where the mistake was
        You're welcome of course and as long as you understand the difference between
        p++ and ++p and the effect it has on your recursive strlen implementation
        everything's fine with me.

        kind regaards,

        Jos

        Comment

        • kalar
          New Member
          • Aug 2007
          • 82

          #5
          I think that with p++ i am calling the function slen always with the same value.Am i right?
          something else, can you tell me if i must include cases for example if the pointer is NULL(the code don't work with NULL pointer) or any other case?

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by kalar
            I think that with p++ i am calling the function slen always with the same value.Am i right?
            Yep, you're right.

            Originally posted by kalar
            something else, can you tell me if i must include cases for example if the pointer is NULL(the code don't work with NULL pointer) or any other case?
            That's an entirely different topic; if you're in the 'defensive programming camp'
            your function might complain big time and even terminate the entire process;
            a more forgiving attitude might just go astray and dump core. It's up to you.
            I'd go for the 'you get what you deserve' attitude.

            kind regards,

            Jos

            Comment

            Working...